如何实现C++代码以使其类似于Lua表格?

huangapple go评论71阅读模式
英文:

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 = &quot;game&quot;,
    Characters = {
        Name = &quot;Characters&quot;
    },
}

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, &quot;Global&quot;);
int mainGameindex = lua_gettop(lua_state);
lua_pushvalue(lua_state, mainGameindex);
std::cout &lt;&lt; &quot;INDEX &quot; &lt;&lt; mainGameindex &lt;&lt; std::endl; //This is a debug message
lua_setglobal(lua_state, &quot;game&quot;); //-&gt; game = {}, it&#39;s a table

lua_pushstring(lua_state, &quot;game&quot;);
lua_setfield(lua_state, -2, &quot;Name&quot;); // -&gt; game.Name = &quot;game&quot;

lua_newtable(lua_state);
lua_setfield(lua_state, -2, &quot;Characters&quot;); // --&gt; game.Characters = {}, it&#39;s a table again

lua_pushstring(lua_state, &quot;Name&quot;);
lua_pushstring(lua_state, &quot;Characters&quot;);
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.

huangapple
  • 本文由 发表于 2023年7月3日 17:39:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定