Last active
August 29, 2015 13:56
-
-
Save tomekc/9134080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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