在 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
最佳答案
你应该使用 lua_pushvalue在 newtable
的值从堆栈中弹出之前复制它:
lua_newTable(L); //Stack: newtable
lua_pushvalue(L, -1); //Stack: newtable, newtable
lua_setfield(-2, "__newindex") //Stack: newtable => newtable.__newindex = newtable
关于C++ 调用 Lua : use setField to point itself?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23735475/