Skip to content

Instantly share code, notes, and snippets.

@rpavlik
Created December 7, 2011 19:08
Show Gist options
  • Save rpavlik/1444159 to your computer and use it in GitHub Desktop.
Save rpavlik/1444159 to your computer and use it in GitHub Desktop.
Quickie example for object-style programming Lua
--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