【问题标题】:Can LUA meta tables assist in detection of nilling object?LUA 元表可以帮助检测 nilling 对象吗?
【发布时间】:2019-08-14 02:33:08
【问题描述】:

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

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 ?

【问题讨论】:

  • 你需要创建一个proxy object
  • 谢谢,我去过那里,但弄乱了语法。很好的参考。

标签: lua lua-table metatable


【解决方案1】:

澄清一下,__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'] 已经有一个非 nil 值,那么 __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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2019-06-10
    相关资源
    最近更新 更多