调用Lua:使用setField来指向自身

C++ Call Lua: use setField to point itself?

本文关键字:setField Lua 使用 调用      更新时间:2023-10-16

在c++中是这样的:

l_newTable(L);                  //Stack: newtable
l_getGlobal(L, "A");            //Stack: newtable A
l_setfiled(-2, "__index")       //Stack: newtable       => newtable.__index = A

这是正常的。然而,如果我想设置一个新的表的__newindex本身,如何编写代码?它需要将__newindex设置为newTable本身,但使用setfield将调用Pop,这意味着:

l_newTable(L);                 //Stack: newtable
l_setfield(-1, "__newindex")   //Stack: -1              => newtable will pop out

你应该在newtable的值从堆栈中弹出之前使用lua_pushvalue来复制它:

lua_newTable(L);                 //Stack: newtable
lua_pushvalue(L, -1);            //Stack: newtable, newtable
lua_setfield(-2, "__newindex")   //Stack: newtable  => newtable.__newindex = newtable