[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A function to create an object using closures
- From: "Evan DeMond" <evan.demond@...>
- Date: Fri, 21 Nov 2008 09:42:29 -0500
On Fri, Nov 21, 2008 at 6:26 AM, Michal Cizmazia <big.sea.cow@gmail.com> wrote:
-- 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
[snip]
Interesting, I never thought of that approach. I feel like it's a little complicated with the "self" pointers and getters for private members. Personally, I like to use a "prototype" sort of approach, using metatables:
function clone(obj) -- or "inherit", "extend", "derive", etc...
local c = {}
setmetatable(c, {__index = obj})
return c
end
Greeting = {}
Greeting.message = "Good morning"
PersonalizedGreeting = clone(Greeting)
PersonalizedGreeting.name = "no name yet"
function Greeting.new()
return clone(Greeting)
end
function Greeting:say()
print (self.message)
end
function PersonalizedGreeting.new()
return clone(PersonalizedGreeting)
end
function PersonalizedGreeting:setName(name)
self.name = name
end
function PersonalizedGreeting:say()
print(self.message .. " " .. self.name)
end
It's a bit wacky, I guess, in that clone() gets used to express both inheritance and instantiation. You create an object to serve as a class, then inherited classes just clone the first class and add/override things.