Question

I want to create a simple nested table with Lua C API. Table is getting filled with the mysql results. However my app is crashing when I am trying to read the table.

Code:

    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);
    }

The above should produce an Lua table:

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

GDB backtrace snippet:

(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

What the wrong here?

Was it helpful?

Solution

Your code only calls lua_settable once, but you want to add both "event" and "timestamp" to the table:

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);
}

You can simplify the code by using 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);
}

Finally, make sure you have enough working stack with 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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top