[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A function to create an object using closures
- From: "Michal Cizmazia" <big.sea.cow@...>
- Date: Mon, 24 Nov 2008 09:24:18 +0100
Thank you for your responses and pointing to higher memory footprint
which increases with number of object instances.
One more question: Can be attributes in a closure (see Example 1)
accessed faster than attributes stored in a table (Example 2)? How
long does take looking up attributes stored in a table compared to
accessing attributes in a closure? Can be this an advantage of
attributes in a closure?
Notes:
"Each object uses one single closure, which is cheaper than one table."
http://www.lua.org/pil/16.5.html
Privacy can be solved using closures.
http://www.lua.org/pil/16.4.html
Michal Cizmazia
-- Example 2
-- object attributes stored in tables
Greeting = { message = "Good morning" }
function Greeting:new(o) return setmetatable( o or {}, { __index = self } ) end
function Greeting:get() return ">" .. self.message end
function Greeting:say() print( self:get() ) end
PersonalizedGreeting = Greeting:new{ name = "anonymous" }
function PersonalizedGreeting:get() return Greeting:get() .. " " ..
self.name end
g = Greeting:new()
p = PersonalizedGreeting:new{ name = "Mike" }
p2 = PersonalizedGreeting:new()
g:say()
p:say()
p2:say()
-- Example 1
-- object attributes stored in closure local variables
function Greeting()
local self = {}
-- Private attributes and methods
local message = "Good morning"
-- Public methods
self.get = function() return message end
self.say = function() print(self.get()) end
return self
end
function PersonalizedGreeting()
local self = Greeting() -- solve inheritace
-- Private attributes and methods
local name
local addName = function(str) return str .. " " .. name end
-- Public methods
self.setName = function(newName) name = newName end
local inherited_get = self.get
self.get = function() return addName(inherited_get()) end -- virtual method
return self
end
g = PersonalizedGreeting()
g.setName("Drew")
g2 = PersonalizedGreeting()
g2.setName("Mike")
g.say()
g2.say()