lua-users home
lua-l archive

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


Is that real code? Does not the C compiler complain
when hitting L2?

2014-04-10 16:44 GMT+02:00 Milind Gupta <milind.gupta@gmail.com>:
> Hi,
>     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
>
>     lua_pushnil(L);
>     while(lua_next(L,2) != 0)
>     {
>         // uses 'key' (at index = -2) and 'value' (at index -1)
>         if(lua_isnumber(L,-2))
>              // Key is a number
>             lua_pushnumber(L2,lua_tonumber(L,-2));
>         else
>             // Key is a string
>             lua_pushstring(L2,lua_tostring(L,-2));
>         // Now push the value
>         if(lua_isnumber(L,-1))
>             // Value is a number
>             lua_pushnumber(L2,lua_tonumber(L,-1));
>         else if(lua_isstring(L,-1))
>             // Value is a string
>             lua_pushstring(L2,lua_tostring(L,-1));
>         else
>             // Value is boolean
>             lua_pushboolean(L2,lua_toboolean(L,-1));
>         lua_pop(L,1);
>     }
>
> Any hints as to why it could be crashing would be really helpful.
>
> Thanks,
> Milind
>
>