Lua C API 嵌套表段错误。

我想用 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

哪里出了错误?

点赞
用户485561
用户485561

你的代码只调用了 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); //设置 event
    lua_pushliteral(L, "timestamp");
    lua_pushnumber(L, atoi(row[1]));
    lua_settable(L, -3); //将 -5 改为 -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);
}
2014-07-31 08:46:46