lualua-tablemeta-method

Metamethod when accessing a key as mutable


__index is called when accessing as immutable :

local foo = bar["foo"];

__newindex is called when access as mutable an index that doesn't exist :

local bar = { }
bar["foo"] = 123 -- calls __newindex
bar["foo"] = 456 -- does NOT call __newindex

Is there a metamethod that can be called when accessing a key as mutable evey time, i.e not only if the key doesn't exist yet?

I would like to create a behavior so that when a users sets a key in a table, it calls a native method instead, regardless if the key already exists or not.


Solution

  • The standard way to do what you want is to use a proxy table, that is an empty table with suitable metamethods to access the actual table. Since the proxy is empty, the metamethods are called every time you get or set fields in it.