Created
December 7, 2011 19:08
-
-
Save rpavlik/1444159 to your computer and use it in GitHub Desktop.
Quickie example for object-style programming Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--See http://www.lua.org/pil/16.html and http://www.lua.org/pil/16.1.html for more information | |
--Table for all "methods" shared between "objects" | |
local objMTindex = {} | |
--method called "greet" | |
function objMTindex:greet() | |
print("Hello from ", self, "aka", self.aka) | |
self.greeted = true | |
end | |
local objMT = { | |
-- when table indexing fails, try looking in objMTindex. | |
__index = objMTindex | |
} | |
function Obj(myname) -- "constructor" | |
return setmetatable({aka = myname, greeted = false}, objMT) | |
end | |
-- Construct two instances | |
a = Obj("the awesome object a") | |
b = Obj("the awesome object b") | |
-- Data access | |
print("a.greeted:", a.greeted) | |
-- Method call | |
a:greet() | |
-- Data access showing mutated state | |
print("a.greeted:", a.greeted) | |
-- Data access showing independent state for each object | |
print("b.greeted:", b.greeted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment