如何自动将默认元表设置为每个新创建的表?

我有一个个人项目和一个纯lua编写的对象模块,为表提供带有filter map等方法的元表,我不想为每一行local foo = {}加载模块和设置元表

原文链接 https://stackoverflow.com/questions/70621128

点赞
stackoverflow用户11740758
stackoverflow用户11740758

你可以设置/使用元方法__newindex,在定义新内容时触发。

对于“每个新表”,正确的位置是:_G

_G = setmetatable(_G,
  {__index = table,
   __newindex = function(tab, key, value)
    print('[__newindex]:', tab, key, value)
    if type(value) == 'table' then
      rawset(tab, key, setmetatable(value, getmetatable(tab)))
    else
      rawset(tab, key, value)
    end
    return
   end
})

--[[ 使用示例:
> a = {}
table: 0xf7ed2380   a   table: 0xf7ed9738
> a:insert('Hi There!')
> print(a:concat())
Hi There!
> a[#a + 1] = {}
[__newindex]:   table: 0xf7ed9738   2   table: 0xf7edbe40
]]

在LuaJIT(Lua 5.1)中不起作用的是什么?

  1. __gc根本不会触发
  2. table.insert({'I(Key [1])am a string in a table'})不会被__newindex触发
2022-11-12 17:19:18