lua-users home
lua-l archive

Re: A function to create an object using closures

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


Hi Michal,
>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
I disagree with this here. If you're only creating one Greeting object or only a few, it might be okay, but I think that if you create many, you're going to have an issue with memory.
Generally a metatable is used in the following form:
Greeting = {};
Greeting.__index = Greeting;
function Greeting.new(message)
 local self = setmetatable({}, Greeting);
 self._message = message;
 return self;
end
function Greeting:get()
 return self._message;
end
function Greeting:say()
 print(self._message);
end
However, there are valid uses for what you specified as well. Both will work; it's up to what you want to do, really. Personally, I'm generally more pressed for memory, so I prefer the metatable approach for frequently used cases.
Regards,
-- Matthew P. Del Buono

AltStyle によって変換されたページ (->オリジナル) /