开发者

Can I detect the moment of a value is just assigned to a table in Lua?

I made an interactive command shell which is operating by Lua interpreter. User input some comm开发者_C百科and, shell calls something like lua_dostring to execute it. I want to allow users to define their own functions in arbitrary table, and save it to separated storage (like a file) automatically. According to the manual, I can get exact source code input by user with lua_Debug.

It looks possible to save the functions sources to some files after all execution done. But I want to save automatically when it's just added/remove.

Can I detect the moment of some value is just added to a table?


Yes. If you have a table tbl, every time this happens:

tbl[key] = value

The metamethod __newindex on tbls metatable is called. So what you need to do is give tbl a metatable and set it's __newindex metamethod to catch the input. Something like this:

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

setmetatable(tbl, captureMeta);

You will have to find a way to set the metatable on the tables of interest, of course.


Here's another way to do this with metatables:

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})

Here's the result:

> t[1]="hello world"
Setting 1 = hello world
> print(t[1])
hello world

Note that I'm using a second table as the index to hold the values, instead of rawset, since __newindex only works on new inserts. The __index allows you to get these values back out from the t_save table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜