lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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?


"Each object uses one single closure, which is cheaper than one table."

Privacy can be solved using closures.

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() .. " " .. end

g = Greeting:new()
p = PersonalizedGreeting:new{ name = "Mike" }
p2 = PersonalizedGreeting:new()

-- 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

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

g = PersonalizedGreeting()
g2 = PersonalizedGreeting()