Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我能检测到Lua中某个值刚刚分配给一个表的时刻吗?_Lua_Variable Assignment_Watch - Fatal编程技术网

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

我能检测到Lua中某个值刚刚分配给一个表的时刻吗?,lua,variable-assignment,watch,Lua,Variable Assignment,Watch,我制作了一个交互式命令shell,它由Lua解释器操作。用户输入一些命令,shell调用类似于lua\u dostring的东西来执行它。我希望允许用户在任意表中定义自己的函数,并自动将其保存到单独的存储(如文件)中。根据手册,我可以通过lua\u Debug获得用户输入的准确源代码 在所有执行完成后,似乎可以将函数源保存到某些文件中。但我想在刚添加/删除时自动保存 我能检测到某个值刚刚添加到表中的时刻吗?是。如果您有一个表tbl,每次发生这种情况时: tbl[key] = value 调用t

我制作了一个交互式命令shell,它由Lua解释器操作。用户输入一些命令,shell调用类似于
lua\u dostring
的东西来执行它。我希望允许用户在任意表中定义自己的函数,并自动将其保存到单独的存储(如文件)中。根据手册,我可以通过
lua\u Debug
获得用户输入的准确源代码

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


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

是。如果您有一个表
tbl
,每次发生这种情况时:

tbl[key] = value
调用
tbl
s元表上的元方法
\uu newindex
。因此,您需要做的是为
tbl
提供一个元表,并将其设置为
\uu newindex
元方法以捕获输入。大概是这样的:

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

setmetatable(tbl, captureMeta);

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

这里有另一种使用元表的方法:

t={}
t_save={}
function table_newinsert(table, key, value)
   io.write("Setting ", key, " = ", value, "\n")
   t_save[key]=value
end
setmetatable(t, {__newindex=table_newinsert, __index=t_save})
结果如下:

> t[1]="hello world"
Setting 1 = hello world
> print(t[1])
hello world
请注意,我使用第二个表作为索引来保存值,而不是
rawset
,因为
\uuu newindex
仅适用于新插入。
\u索引
允许您从
t\u save
表中获取这些值