首页 > 解决方案 > 有没有办法知道是否在lua中的数组中添加或删除了一个键?

问题描述

local t = {}
local mt = setmetatable({
        -- some meta method to know when a key is added or lost and prints a message
      }, t)

有没有办法做到这一点。我和某人讨论过这个问题,他们说我不能只使用元方法,还可以使用代理。我对如何使这项工作有些困惑。任何人都可以帮忙吗?

谢谢

标签: luametatablemeta-method

解决方案


要在 lua 中跟踪表键,metatable 中有 2 个最重要的键:__index__newindex.

__newindex如果找不到这样的键,则用于在表中创建新键。__index如果表中没有这样的键,则用于获取值。

可以跟踪创建,但不能跟踪分配,因此__newindex无法跟踪密钥删除:

<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">

local t={}
setmetatable(t, {
  __newindex = function(self, key, value)
    print('Added Key:'..key,'Value:'..value)
    rawset(self, key, value)
  end
})

t.test = 'test'
t.test = nil -- delete not tracked
t.test = 'test2'

</script>

使用代理表__newindex__index我们可以跟踪每个分配:

<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">

local t={}
local proxytable={}
setmetatable(t, {
  __newindex = function(self, key, value)
    if proxytable[key] then
      if value == nil then
        print('Deleted Key:'..key)
      else
        print('Changed Key:'..key,'Value:'..value)
      end
    else
      print('Added Key:'..key,'Value:'..value)
    end
    rawset(proxytable, key, value)
  end,
  __index = proxytable
})

t.test = 'test'
t.test = nil
t.test = 'test2'
t.test = 'test3'
t.test = nil

</script>

如果你想用 , 枚举表键pairs()ipairs()那么你需要使用元键__pairs__ipairs因为原始表总是空的。


推荐阅读