Problem with lua_isstring iterating for table in table

I try to write a table to an ini file, everything worked until I added a line lua_tostring(L, -2) then lua_next(L, -2) began to give out an error. How this line can influence, in my understanding, I just take the value from the stack and no more. How I can fix it?

{
    // Push an initial nil to init lua_next
    lua_pushnil(inOutState);
    // Parse the table at index
    while (lua_next(inOutState, -2))
    {
        if (lua_isstring(inOutState, -1)) {
            string key = lua_tostring(inOutState, -2);
            string value = lua_tostring(inOutState, -1);
            inIniTree.put(suffix + key, value);
        }
        else if (lua_istable(inOutState, -1)) {
            suffix += lua_tostring(inOutState, -2); !!!!!! without this line function is working well !!!!!!!
            setDataInIni(inOutState, inIniTree, suffix);
        }

        // Pop value, keep key
        lua_pop(inOutState, 1);
    }
    return;
}

Upvotes: 1

Views: 190

Answers (1)

Darius
Darius

Reputation: 1180

lua_tostring() replaces value in stack if value is not of type string. It means you changed key for lua_next(). You must copy value with lua_pushvalue() and then convert it to string.

if (lua_isstring(inOutState, -1)) {
  lua_pushvalue(inOutState, -2);
  string key = lua_tostring(inOutState, -1);
  lua_pop(L, 1);
  string value = lua_tostring(inOutState, -1);
  inIniTree.put(suffix + key, value);
}
else if (lua_istable(inOutState, -1)) {
  lua_pushvalue(inOutState, -2);
  suffix += lua_tostring(inOutState, -1);
  lua_pop(L, 1);
  setDataInIni(inOutState, inIniTree, suffix);
}

Upvotes: 1

Related Questions