lua-users home
lua-l archive

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


On 2012-10-15 4:50 PM, "Marc Lepage" <mlepage@antimeta.com> wrote:
>
> I'm wondering if there's a good way to know if a metatable for an object is changed.
>
> Suppose the case is that the metatable is not protected. An object wants to wrap its metatable with another, so it can be extended. But if the metatable is changed, it needs to re-wrap it.
>
> Is there a good way the object can know when that occurs, so it can perform the re-wrapping?
>
> I thought of re-writing setmetatable to perform a notification. I guess that would work, but it seems heavy-handed.
>
> I thought of requiring clients to call a different function that does the notification (or even the wrapping), but that requires editing clients.
>
> It would be cool if objects could implement __setmetatable, which would be called if available, when the metatable is set. It would effectively replace __metatable, because you could always just ignore it (do nothing) if you don't want the metatable to be changeable.
>
> Does anyone have advice on this topic? Thanks.

Wrapping setmetatable to call some type of notification metamethod on the old metatable before applying the new one seems like the best idea. Then you can do things like filter or modify the new metatable (have the notification method take the new table as parameter and return a value that then gets set as the new metatable), while client code doesn't need to know anything about it.

Of course when you modify a global/standard method you have to consider modules loaded earlier that might keep a local reference, lua_setmetatable, and potential client headache when they aren't aware of the new behaviour...