我可以检测到一个值刚刚分配给Lua中的表的时刻吗?

Eon*_*nil 4 lua watch variable-assignment

我创建了一个由Lua解释器操作的交互式命令shell.用户输入一些命令,shell调用类似lua_dostring执行它的东西.我想允许用户在任意表中定义自己的函数,并自动将其保存到单独的存储(如文件)中.根据手册,我可以得到用户输入的确切源代码lua_Debug.

完成所有执行后,可以将函数源保存到某些文件中.但我想在添加/删除时自动保存.

我可以检测到某个值刚刚添加到表中的时刻吗?

Nic*_*las 5

是.如果你有一张桌子tbl,每次发生这种情况:

tbl[key] = value
Run Code Online (Sandbox Code Playgroud)

元方法__newindextbl小号元表被调用.所以你需要做的是给tblmetatable并设置它的__newindexmetamethod来捕获输入.像这样的东西:

local captureMeta = {}
function captureMeta.__newindex(table, key, value)
    rawset(table, key, value)
    --do what you need to with "value"
end

setmetatable(tbl, captureMeta);
Run Code Online (Sandbox Code Playgroud)

当然,您必须找到一种在感兴趣的表上设置元表的方法.