Hi,
Is there way to add a property observer in Lua just like Swift does for WillSet and DidSet with properties?
For example, I have a object of display.newText and whenever I change it’s text property. I need to do something other as well?
I know I can add a method like setText() or something but I’m looking for property observers in Lua language.
Thanks in advance.
Regards,
Usman Mughal
in lua this is done with metatables (using the metamethods __index for get, and __newIndex for set)
in fact, and complicating things greatly, the text “property” of a display.newText already has just such an “observer” method in place - when you change the .text value of a display.newText display object, all sorts of things happen under the hood, and the text object’s internal representation is completely recreated (ie, it’s mask is “re-rendered”).
it is possible (despite docs to the contrary) but non-trivial to directly alter the metatable of a display object, but you have to be very careful to preserve the existing corona metatable, and i wouldn’t recommend it except in extraordinary circumstances.
it is essentially equivalent, but conceptually far easier, to first “wrap” your text object in a proxy table, then implement your metamethod observers on THAT table, and just pass through everything else.
in lua this is done with metatables (using the metamethods __index for get, and __newIndex for set)
in fact, and complicating things greatly, the text “property” of a display.newText already has just such an “observer” method in place - when you change the .text value of a display.newText display object, all sorts of things happen under the hood, and the text object’s internal representation is completely recreated (ie, it’s mask is “re-rendered”).
it is possible (despite docs to the contrary) but non-trivial to directly alter the metatable of a display object, but you have to be very careful to preserve the existing corona metatable, and i wouldn’t recommend it except in extraordinary circumstances.
it is essentially equivalent, but conceptually far easier, to first “wrap” your text object in a proxy table, then implement your metamethod observers on THAT table, and just pass through everything else.