Lua C API:插入表元素导致调试断言失败。

函数成功返回并且我可以使用表中的值,但是出现了“Debug Assertion Failed”的错误并且程序停止。我知道断言的问题出现在for循环中,但是不知道该如何修复。谢谢您提前的帮助。

static int l_xmlNodeGetValues(lua_State *L)
{
  int iDocID = luaL_checkint(L, 1);
  const char *pszNodeName = luaL_checkstring(L, 2);

  CConfig *file = docs.at(iDocID);
  int i = 1;
  lua_newtable(L);
  for( TiXmlElement *e = file->GetRootElement()->FirstChildElement(pszNodeName);
       e; e = e->NextSiblingElement(pszNodeName) )
  {
      lua_pushstring(L, e->GetText());
      lua_rawseti(L,-2,i);
      i++;
  }
  return 1;
}

编辑: 当我将int i设置为0时,它可以工作,但会忽略最后一个元素。如果i == 1时,它为什么不起作用?

lua_rawseti(L,-2,i);i == 1 时出现了断言失败的错误。

因为没有解决方案可以解决我的问题,所以我将尝试描述它的工作原理以及这两种情况的输出。我只是想从XML文件中获取指定节点的所有值:

<root>
    <node>A</node>
    <node>B</node>
    <node>C</node>
    <node>D</node>
</root>

脚本看起来像这样:

xmlfile = xmlOpenFile( "myfile.xml", "root" );
if ( xmlfile ) then
    for _, v in ipairs( xmlNodeGetValues( xmlfile, "node" ) ) do
        print( v );
    end
end

问题:

int i = 1;

输出:

A B C D !!!debug assertion failed!!!

------------------------------------------------------

int i = 0;

输出:

B C D 没有错误...

点赞
用户1022729
用户1022729

你确定你的代码没有错误吗?

我刚刚检查了这个解决方案,它似乎可以工作,代码打印了刚刚创建的表格:

#include <lua.hpp>
#include <stdio.h>

static int fun(lua_State * L)
{
    int i;
    lua_newtable(L);
    for(i = 0; i < 10; i++ )
    {
        lua_pushstring(L, "A");
        lua_rawseti(L,-2,i);
    }

    lua_setglobal(L, "t");
    return 1;
}

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);

    fun(L);

    if (luaL_dostring(L, "for k,v in ipairs(t) do print(k,v); end;\n"))
    printf("%s\n",luaL_checkstring(L, -1));

    lua_close(L);
}
2013-08-12 15:08:58