Skip to content

Instantly share code, notes, and snippets.

@tomekc
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomekc/9134080 to your computer and use it in GitHub Desktop.
Save tomekc/9134080 to your computer and use it in GitHub Desktop.
-- 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