4

__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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Virus721
  • 8,061
  • 12
  • 67
  • 123

3 Answers3

3

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks. I forgot to mention that I don't need that the values the user places in the table be actual present in the table. These values would be stored in native code, so having an empty table is what I need because it would trigger the __newindex everytime and wouldn't duplicate the data in both C and Lua code. I'll go far that. – Virus721 Mar 10 '16 at 13:16
1

I am rather sure there are no such metamethods you ask for. But you can try make a workaround to get what you want.

For example you can try to use the __call metamethod in this way:

local mt = {}
function mt.__call(tbl, key, val)
    -- this is called every time you use bar(key, val)
    tbl[key] = val
end

local bar = setmetatable({}, mt)

bar("foo", 123)
bar("foo", 456)

print(bar.foo)

Or you could use a function in some other way to achieve this.

Rochet2
  • 1,146
  • 1
  • 8
  • 13
  • Thanks. Though I want to keep the subscript syntax, so i'll just do what lhf suggests and keep the table empty, which is what I need anyway. – Virus721 Mar 10 '16 at 13:17
0

Immutability doesn't exist in Lua, you just mean indexed accessing and assigning. Lua 5.3 states...

This event happens when table is not a table or when key is not present in table.

...for both cases.

Your best option would be to store values in another table or subtable of yours.

Youka
  • 2,646
  • 21
  • 33