Search code examples
clualua-table

Iterate through Lua Table


I am trying to iterate through a lua table but I keep getting this error:

invalid key to 'next'

I know that index starts off as -8 and I know that there is a table there because it gets the first (and only) value in it. However, it tries to loop round again even though I know there is only one string in the table.

if (lua_istable(L, index))
{
    lua_pushnil(L);

    // This is needed for it to even get the first value
    index--;

    while (lua_next(L, index) != 0)
    {
        const char *item = luaL_checkstring(L, -1);
        lua_pop(L, 1);

        printf("%s\n", item);
    }
}
else
{
    luaL_typerror(L, index, "string table");
}

Any help would be appreciated.

This works fine when I use a positive index (as long as I don't remove 1 from it)

Edit: I've noticed that I don't get this error if I leave the value of item alone. Only when I start reading the value of item do I get this error. When I've got the value from the table, I call another Lua function, could this be disrupting lua_next?


Solution

  • Do not use luaL_checkstring with negative arguments. Use lua_tostring instead.

    Also, make sure the stack remains the same after you call a function in the loop: lua_next expects the previous table key at the top of the stack so that it can resume the traversal.