Key metametad as volatile

__index called upon access as immutable:

local foo = bar["foo"];

__newindex called when accessed as a mutable index that does not 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 the key as a variable evey time, i.e. not only if the key does not exist yet?

I would like to create a behavior so that when a user sets a key in a table, he calls his own method, regardless of whether the key exists or not.

+4
source share
3 answers

, , - -, . , , .

+3

, , . , , .

, __call :

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)

.

+1

Lua , . Lua 5.3 ...

, .

... .

- .

0

All Articles