如果__newindex指向一个函数的话,Lua就会调用那个函数,table,key,value会作为参数传递给函数。 可以使用rawset函数更新表的数据: mytable = setmetatable({key1 = "value1"}, { __newindex = function(mytable, key, value) rawset(mytable, key, "\""..value.."\"") end }) mytable.key1 = "new ...
This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4). lua_settable 前栈情况 ---top--- `Val' 1 table ---end--- lua_settable(L, -3) 之后 ---top--- table ---end---...
lua lua_settable void lua_settable (lua_State *L, int index); Does the equivalent tot[k] = v, wheretis the value at the given index,vis the value at the top of the stack, andkis the value just below the top. This function pops both the key and the value from the stack. As ...
lua lua_settable void lua_settable (lua_State *L, int index); Does the equivalent tot[k] = v, wheretis the value at the given index,vis the value at the top of the stack, andkis the value just below the top. This function pops both the key and the value from the stack. As ...
调用luaV_settable设置表字段,其中: 调用luaV_fastset设置字段,如果失败则调用luaV_finishset,这里面就会使用元方法。 通过fasttm或luaT_gettmbyobj得到元方法后,判断它是否为函数,如果为函数则调用luaT_callTM,否则它应该是一个表,则继续这个过程。
lua_settable(L, -3)<== mytable[1] = "abc", pop key & value lua_rawget: 用法同lua_gettable,但更快(因为当key不存在时不用访问元方法__index) lua_rawset: 用法同lua_settable,但更快(因为当key不存在时不用访问元方法__newindex)
//lua_settable(L, 1); //code9 lua_pushnumber(L, 19); lua_setfield(L, 1, "age"); //code10 //lua_pushstring(L, "age"); //lua_gettable(L, 1); code11 lua_getfield(L, 1, "age"); StackDump(L, 5); printf("setglobal age: %d\n", (int)lua_tointeger(L, -1)); ...
function 类名:new(o) o = o or {} setmetatable(o,{__index = self}) return oend 或者 function 类名:new(o) o = o or {} setmetatable(o,self) self.__index = self return oend 相比之下,第二种写法可以多省略一个 table,另外有一点我觉得有必要说明的就是 lua 中的元方法...
lua_settop(L, 0); //code5 lua_getglobal(L, "nameTable"); code6 //lua_pushstring(L, "sex"); //lua_gettable(L, -2); //lua_pushstring(L, "age"); //lua_gettable(L, -3); code7 lua_getfield(L, -1, "sex"); lua_getfield(L, -2, "age"); ...
LUA中table操作(主要是对它stack的理解) lua_getglobal( L, "myTable" ); // 假设我有这么个全局表,这个调用会将该表放在栈顶 lua_pushstring( L, "age" ); // "age"压到栈顶 lua_pushnumber( L, 29 ); // "29"压到栈顶 lua_settable( L, -3 ); // 到此,这个myTable现在处于-3位置,...