unresolved_external
unresolved_external

Reputation: 2018

How to return two or more tables from lua function?

I would be really appreciative if someone explain me how lua-C stack works when lua function called from C returns two tables or table which has nested table inside

when I am trying to do it it seems to look fine but only at first glimpse:

if ( lua_istable(L, -1) )
        printf("its OK\n");

    if ( lua_istable(L, -2) )
        printf("its OK\n");

    lua_pushnil(L);

        while ( lua_next(L, -2) )
        {
            if(lua_isnumber(L, -1)) 
            {
                int i = (int)lua_tonumber(L, -1);
                const char *key = lua_tostring(L, -2); 
                printf("%d %s \n", i, key); 
            }
            lua_pop(L, 1);
        }
        lua_pop(L, 1);

In this case I got two messages that first table is on level -1, on the second one is on level -2, but afterthis code, when I am trying to get the next table my program crashes when I check stack on table existence

for ( int i = -2; ; --i)
            if ( lua_istable(L, i) )
                printf("its %d OK\n", i);

I got following result:

its -233 OK
its -645 OK
its -1245 OK
its -1549 OK
its -2807 OK
its -2815 OK
its -2816 OK

can somebody help me out with this ?

Upvotes: 1

Views: 438

Answers (1)

Doug Currie
Doug Currie

Reputation: 41220

Note that when lua_next returns 0 is has popped the key, and pushed nothing, so at the end of the while loop you have your two tables on the stack.

The lua_pop after your while loop is popping the top table off the stack.

The subsequent for loop is starting at index -2 which is past the table, and could contain anything. Furthermore, the for loop will never terminate.

Upvotes: 3

Related Questions