lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Response is inline.

Milind Gupta <milind.gupta@gmail.com> writes:

>     I am traversing a table 2 times in my C function. 1st to validate
> whether all keys and values are of certain types and then the next time to
> act on them. In the next loop lua_next crashes. The sample table is just 1
> element with a string key and a number value. Here is the code of the table
> traversal. The table is the second argument to the function hence it uses 2
> in lua_next:
>
>     lua_pushnil(L);  // first key
>     while (lua_next(L, 2) != 0)
>     {
>         // uses 'key' (at index -2) and 'value' (at index -1)
>
>         // Key must be a number or a string
>         // Value can be a number. string, or boolean
>         if(!lua_isnumber(L,-2) && !lua_isstring(L,-2))
>         {
>             lua_pushnil(L);
>             lua_pushstring(L,"Table key is not a number or a string");
>             return 2;    // 2 results pushed on the stack
>         }
>         if(!lua_isnumber(L,-1) && !lua_isstring(L,-1) &&
> !lua_isboolean(L,-1))
>         {
>             lua_pushnil(L);
>             lua_pushstring(L,"Table value is not a number, string, or
> boolean");
>             return 2;    // 2 results pushed on the stack
>         }
>         lua_pop(L, 1);
>     }
>     lua_pop(L,1);   // Pop the last key

This last is your problem, I would guess.  lua_next() consumes the key
and pushes nothing on the final invocation.

-- 
Michael Welsh Duggan
(mwd@cert.org)