Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Quickie example for object-style programming Lua
--See and 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
local objMT = {
-- when table indexing fails, try looking in objMTindex.
__index = objMTindex
function Obj(myname) -- "constructor"
return setmetatable({aka = myname, greeted = false}, objMT)
-- Construct two instances
a = Obj("the awesome object a")
b = Obj("the awesome object b")
-- Data access
print("a.greeted:", a.greeted)
-- Method call
-- 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