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

标签 lua lua-table metatable

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

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/

相关文章:

intellij-idea - 远程调试 Idea 不适用于 openresty

Lua类不工作

eclipse - LuaEclipse 插件中 Lua 的语法高亮显示

function - 定义函数参数的默认值

lua - 如何创建一个函数来返回传递给它的第一个非零、非空字符串?

lua - 通过变量从Lua表中调用值

arrays - 将数组作为 Fortran 中的函数参数传递给 lua

Lua 元表不一致

Lua "attempt to index a nil value": indexing nested tables, 其中几个表可能不存在(使用 __index 和 __newindex 元方法)

regex - 使用 lua 脚本解析 csv