lua-users home
lua-l archive

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


-- What do you think about the following object-oriented approach,
-- in which a function is used to create an object using closures?
-- I am looking forward to your responses.
-- Michal Cizmazia

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