public
Created

Quickie example for object-style programming Lua

  • Download Gist
mtclasses.lua
Lua
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
--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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.