1

I'm using the following function to traverse a Lua table and read it into a `Json::Value

Json::Value EncodeTable(lua_State* L, int index){
    Json::Value node;
    //The solution: change lua_pushvalue(L, -1) to lua_pushvalue(L, index)
    lua_pushvalue(L, index);
    lua_pushnil(L);
    while(lua_next(L, -2)){
        lua_pushvalue(L, -2);
        if(lua_isnumber(L, -1)){
            if(lua_isstring(L, -2)){
                node[(int)lua_tonumber(L, -1)-1] = lua_tostring(L, -2);
            }else if(lua_isnumber(L, -2)){
                node[(int)lua_tonumber(L, -1)-1] = lua_tonumber(L, -2);
            }else if(lua_isnil(L, -2)){
                node[(int)lua_tonumber(L, -1)-1] = Json::Value();
            }else if(lua_istable(L, -2)){
                node[(int)lua_tonumber(L, -1)-1] = EncodeTable(L, -2);
            }
        }else{
            if(lua_isstring(L, -2)){
                node[lua_tostring(L, -1)] = lua_tostring(L, -2);
            }else if(lua_isnumber(L, -2)){
                node[lua_tostring(L, -1)] = lua_tonumber(L, -2);
            }else if(lua_isnil(L, -2)){
                node[lua_tostring(L, -1)] = Json::Value();
            }else if(lua_istable(L, -2)){
                node[lua_tostring(L, -1)] = EncodeTable(L, -2);
            }
        }
        lua_pop(L, 2);
    }
    lua_pop(L, 1);
    return node;
}

And it all works fine, until there is a nested table, then it segfaults. Running LLDB just gave me some assembly errors, so that didn't help either. Does anyone know what I'm doing wrong?

EDIT

LLDB gives me this:

* thread #2: tid = 0x5a47, 0x00007f902f99f280 liblua5.2.so.0
    frame #0: 0x00007f902f99f280 liblua5.2.so.0
-> 0x7f902f99f280:  movzbl 11(%rdi), %ecx
   0x7f902f99f284:  movq   (%rsi), %rdx
   0x7f902f99f287:  movl   $1, %eax
   0x7f902f99f28c:  movq   32(%rdi), %r8
Dirk
  • 2,094
  • 3
  • 25
  • 28

0 Answers0