Skip to content

Instantly share code, notes, and snippets.

@tomekc
Last active Aug 29, 2015
Embed
What would you like to do?
-- Table based object with method
function newPerson(name)
local M = {
name = name,
age = 0,
}
M.greet = function (self)
print ("This is " .. self.name .. ", I am " .. self.age)
end
M.age = math.random(100)
return M
end
local p1 = newPerson("Adam")
p1.age = 6
p1:greet()
-- ------------------------------------------------------------------
-- Closure based object with method
function Persona(name)
local self = {}
self.name = name
self.age = math.random(100)
function self.greet()
print ("This is " .. self.name .. ", I am " .. self.age)
end
return self
end
local p2 = Persona("Beth")
local p3 = Persona("Charlie")
p2.age = 12
-- Here we don't have to call using ':' as "self" is already stored in the methods.
p2.greet()
p3.greet()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment