1

函数成功返回,我可以使用表中的值,但出现错误“调试断言失败”,这就结束了。我知道 assert 的问题出在 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);出现断言失败时 我== 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

问题:

诠释 i = 1;

输出:

A B C D !!!调试断言失败!!!

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

诠释 i = 0;

输出:

B C D 没有错误...

4

1 回答 1

2

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

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

#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-12T15:08:58.233 回答