英文:
How to implement C++ code in order to be similar to Lua table?
问题
以下是已翻译的内容:
luaL_newmetatable(lua_state, "Global");
int mainGameindex = lua_gettop(lua_state);
lua_pushvalue(lua_state, mainGameindex);
std::cout << "INDEX " << mainGameindex << std::endl; // 这是一个调试消息
lua_setglobal(lua_state, "game"); // -> game = {}, 这是一个表
lua_pushstring(lua_state, "game");
lua_setfield(lua_state, -2, "Name"); // -> game.Name = "game"
lua_newtable(lua_state);
lua_setfield(lua_state, -2, "Characters"); // --> game.Characters = {}, 这是一个表
lua_pushstring(lua_state, "Name");
lua_pushstring(lua_state, "Characters");
lua_settable(lua_state, -3);
希望这能帮助解决你的问题。如果还有其他疑问,请随时提出。
英文:
I am here for help because I'm trying to setup array table that is similar to my lua table like this:
game = {
Name = "game",
Characters = {
Name = "Characters"
},
}
Still, It gives me nill from game.Characters.Name, and game.Name changes its variable into Characters by "lua_pushstring(lua_state, "Characters")"
Here's my unfinished C++ code where I want it to be similar to the table in Lua code
luaL_newmetatable(lua_state, "Global");
int mainGameindex = lua_gettop(lua_state);
lua_pushvalue(lua_state, mainGameindex);
std::cout << "INDEX " << mainGameindex << std::endl; //This is a debug message
lua_setglobal(lua_state, "game"); //-> game = {}, it's a table
lua_pushstring(lua_state, "game");
lua_setfield(lua_state, -2, "Name"); // -> game.Name = "game"
lua_newtable(lua_state);
lua_setfield(lua_state, -2, "Characters"); // --> game.Characters = {}, it's a table again
lua_pushstring(lua_state, "Name");
lua_pushstring(lua_state, "Characters");
lua_settable(lua_state, -3);
My thought was "game.Characters.Name = "Characters"". Without it, it would also work.
So, Can anyone point out what am I doing wrong, or just replace my C++ code with your fixed code.
EDIT: I re-explain because after I tried to start debug, no error, but still a problem because game.Name changes its variable from "game" to "character".
答案1
得分: 3
在这里,你假设你有一个位于索引`-3`的表,但实际上没有。之前的`lua_setfield`已经从堆栈中弹出了这个表。在插入字段之前,你需要显式地推送对`game.Characters`的另一个引用。
英文:
lua_settable(lua_state, -3);
Here you assume that you have the table at index -3
, but you don't.
Previous lua_setfield
has popped this table from the stack.
You need to explicitly push another reference to game.Characters
before inserting a field into it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论