gpt4 book ai didi

c++ - Lua C API 嵌套表段。过错

转载 作者:太空狗 更新时间:2023-10-29 21:20:14 24 4
gpt4 key购买 nike

我想用 Lua C API 创建一个简单的嵌套表格。表中充满了 mysql 结果。但是,当我尝试读取表格时,我的应用程序崩溃了。

代码:

    int i = 0;
lua_newtable(L);
while(row = mysql_fetch_row(result))
{
lua_newtable(L);
lua_pushliteral(L, "event");
lua_pushnumber(L, atoi(row[0]));
lua_pushliteral(L, "timestamp");
lua_pushnumber(L, atoi(row[1]));
lua_settable(L, -5);
lua_rawseti(L, -2, ++i);
}

上面应该产生一个 Lua 表:

{
{event = 1, timestamp = 1234567890},
{event = 2, timestamp = 1234567890},
{event = 2, timestamp = 1234567890},
[..]
}

GDB 回溯片段:

(gdb) bt
#0 luaH_getnum (t=0x3c7db040, key=1) at ltable.c:444
#1 0x0825f94e in luaH_setnum (L=0x3c7d5ca0, t=0x3c7db040, key=1) at ltable.c:500
#2 0x08257fd5 in lua_rawseti (L=0x3c7d5ca0, idx=-2, n=1) at lapi.c:593

这里有什么问题?

最佳答案

您的代码只调用了一次 lua_settable,但您希望将 “event”“timestamp” 添加到表中:

int i = 0;
lua_newtable(L);
while(row = mysql_fetch_row(result))
{
lua_newtable(L);
lua_pushliteral(L, "event");
lua_pushnumber(L, atoi(row[0]));
lua_settable(L, -3); //Set event
lua_pushliteral(L, "timestamp");
lua_pushnumber(L, atoi(row[1]));
lua_settable(L, -3); //changed `-5` to `-3`
lua_rawseti(L, -2, ++i);
}

可以使用lua_setfield来简化代码:

int i = 0;
lua_newtable(L);
while(row = mysql_fetch_row(result))
{
lua_newtable(L);
lua_pushnumber(L, atoi(row[0]));
lua_setfield(L,-2,"event");
lua_pushnumber(L, atoi(row[1]));
lua_setfield(L,-2,"timestamp");
lua_rawseti(L, -2, ++i);
}

最后,使用 luaL_checkstack 确保您有足够的工作堆栈:

luaL_checkstack(L,3,nullptr);
int i = 0;
lua_newtable(L);
while(row = mysql_fetch_row(result))
{
lua_newtable(L);
lua_pushnumber(L, atoi(row[0]));
lua_setfield(L,-2,"event");
lua_pushnumber(L, atoi(row[1]));
lua_setfield(L,-2,"timestamp");
lua_rawseti(L, -2, ++i);
}

关于c++ - Lua C API 嵌套表段。过错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com