gpt4 book ai didi

lua - LUA meta tables 可以协助检测 nilling object 吗?

转载 作者:行者123 更新时间:2023-12-05 07:24:36 25 4
gpt4 key购买 nike

我想知道您是否可以通过元表检测对象的空化?

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com