lua-users home
lua-l archive

Re: OOP sortof

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


On Sat, Jan 1, 2011 at 3:33 PM, Philippe Lhoste <PhiLho@gmx.net> wrote:
> Scala (to remain in the JVM realm) resolved that quite elegantly: just leave
> the variables in the open, and should you add code around access (get or
> set), you can do it without disturbing calling code.
> That's indeed a point that a modern language should address elegantly.
Yes, there are cases where the property pattern is the most elegant
solution - VB, borrowed by Delphi, brought back into MS by Delphi's
creator when he did C#.
With Lua one can write general setters and getters. For instance, a
common pattern is some GUI element where setting a property must cause
the element to update itself. Classic OOP would look like this,
repeated for each property:
function Box.set_width(x)
 if x ~= self.width then
 self.width = x
 self:update()
 end
end
A more dynamic solution could look like this:
local property = {width=true,height=true,text=true}
function Box.__newindex(self,prop,value)
 if property[prop] then
 local name = '_'..prop -- i.e. actual field is _width, etc
 if self[name] ~= value then
 self[name] = value
 self:update()
 end
 else
 error("not a property or method",2)
 end
end
steve d.

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