首页 > 解决方案 > lua_isstring 迭代表中表的问题

问题描述

我尝试将表写入ini文件,一切正常,直到我添加一行lua_tostring(L, -2)然后lua_next(L, -2)开始发出错误。这条线如何影响,在我的理解中,我只是从堆栈中获取值,仅此而已。我该如何解决?

{
    // 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;
}

标签: c++lualua-table

解决方案


lua_tostring() 如果值不是字符串类型,则替换堆栈中的值。这意味着您更改了lua_next(). 您必须复制值,lua_pushvalue()然后将其转换为字符串。

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);
}

推荐阅读