访问可变键时的元方法
Metamethod when accessing a key as mutable
__index
在作为 immutable 访问时被调用:
local foo = bar["foo"];
__newindex
当作为 mutable 访问不存在的索引时被调用:
local bar = { }
bar["foo"] = 123 -- calls __newindex
bar["foo"] = 456 -- does NOT call __newindex
是否有元方法可以在每次以 mutable 访问密钥时调用,即不仅在密钥尚不存在时调用?
我想创建一个行为,以便当用户在 table 中设置一个键时,它会调用本地方法,而不管该键是否已经存在。
我很确定没有您要求的此类元方法。
但是你可以尝试做一个变通方法来得到你想要的。
例如,您可以尝试以这种方式使用 __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)
或者您可以通过其他方式使用函数来实现此目的。
Lua 中不存在不变性,您只是指索引访问和分配。 Lua 5.3 个州...
This event happens when table is not a table or when key is not
present in table.
...对于这两种情况。
您最好的选择是将值存储在您的另一个 table 或子table 中。
做你想做的事情的标准方法是使用代理 table,这是一个空的 table 和 suitable 元方法来访问实际的 table .由于代理是空的,每次在其中获取或设置字段时都会调用元方法。
__index
在作为 immutable 访问时被调用:
local foo = bar["foo"];
__newindex
当作为 mutable 访问不存在的索引时被调用:
local bar = { }
bar["foo"] = 123 -- calls __newindex
bar["foo"] = 456 -- does NOT call __newindex
是否有元方法可以在每次以 mutable 访问密钥时调用,即不仅在密钥尚不存在时调用?
我想创建一个行为,以便当用户在 table 中设置一个键时,它会调用本地方法,而不管该键是否已经存在。
我很确定没有您要求的此类元方法。 但是你可以尝试做一个变通方法来得到你想要的。
例如,您可以尝试以这种方式使用 __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)
或者您可以通过其他方式使用函数来实现此目的。
Lua 中不存在不变性,您只是指索引访问和分配。 Lua 5.3 个州...
This event happens when table is not a table or when key is not present in table.
...对于这两种情况。
您最好的选择是将值存储在您的另一个 table 或子table 中。
做你想做的事情的标准方法是使用代理 table,这是一个空的 table 和 suitable 元方法来访问实际的 table .由于代理是空的,每次在其中获取或设置字段时都会调用元方法。