我想知道您是否可以通过元表检测对象的空化?
foo = {}
foo_mt = {
__newindex = function (t, k, v)
print (k, v)
rawset (t, k, v)
end
}
setmetatable (foo, foo_mt)
foo ['oof'] = 3
outputs: oof 3
foo ['oof'] = nil
__newindex will not be called, so is there another meltable method ?
最佳答案
澄清一下,__newindex 仅在前一个值为 nil 时触发。所以下面的代码会触发两次__newindex:
foo = {}
foo_mt = {
__newindex = function (t, k, v)
print (k, v)
rawset (t, k, v)
end
}
setmetatable (foo, foo_mt)
foo['oof'] = nil
foo['oof'] = nil
如果 foo['oof'] 已经有一个非零值那么 __newindex 将不会被调用(因为索引已经存在)。
但是,是的,如果您想像 Egor 指出的那样捕获对您的表的所有修改,您需要类似空代理表的东西。
proxy = {}
foo = {}
foo_mt = {
__newindex = function (t, k, v)
print (k, v)
rawset (proxy, k, v)
end,
__index = function(t, k)
return rawget(proxy, k)
end
}
setmetatable (foo, foo_mt)
foo['ok'] = true
foo['ok'] = nil
关于lua - LUA meta tables 可以协助检测 nilling object 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310898/