从C++传递Lua表格到.Lua脚本

3

我已经花费了过去6个小时来解决这个问题,但是没有任何进展:s

我希望能够在c++文件中创建一个lua表,并将其传递到具有以下lua函数的lua脚本文件中:

function MTable (t) 
local n=#t
    for i=1,n do 
      print(t[i]) 
    end
end

我动态创建了一个包含两个字符串的一维数组:

 lua_newtable(L);
 lua_pushstring(L,"10.10.1.1");
 lua_pushstring(L,"10.10.1.2");
 lua_rawseti(L,-3,2);
 lua_rawseti(L,-2,1);

现在我把表格放在栈的顶部。 我通过编写以下代码进行验证: if (lua_istable(L, lua_gettop(L))),它返回1,这意味着它是一个表格。

然后我做了这件事:

lua_getglobal(L, "MTable");    // push the lua function onto the stack

uint32_t   result = lua_pcall(L, 1, 0, 0);  //argument 1 is for the table
 if (result) {
 printf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
         exit(1);
}

我遇到了这个错误:

运行脚本失败:尝试调用一个表值

请注意,该文件还有其他几个函数,我已经成功地从C++中调用了它们。

请问有人能帮我解决这个错误吗?这可能是LUA的一个bug吗?因为我按照步骤做得非常正确...我猜!


这个问题已经在Lua邮件列表中得到了回答。 - lhf
1个回答

4

在参数之前,该函数必须是栈中的第一个

你可以选择:

  1. push the function to call on the stack before generating the table, e.g.:

    lua_getglobal(L, "MTable");
    ...generate table on stack...
    int result = lua_pcall(L, 1, 0, 0);
    
  2. Do in the order you do now, and then just swap the arg and the function prior to doing the pcall:

    ...generate table on stack...
    lua_getglobal(L, "MTable");
    lua_insert (L, -2);   // swap table and function into correct order for pcall
    int result = lua_pcall(L, 1, 0, 0);
    

谢谢!它像魔法一样奏效了!我还有一个问题,C语言如何从Lua中获取表格? 我编辑了Lua脚本以返回t。到目前为止,Lua将t推入堆栈。C语言如何取出它?我读了另一个解决这个问题的线程,但是我无法理解解决方案中的任何一个词。我只知道我必须编写一个接受Lua状态参数的C函数,但我不知道该怎么做!你知道吗? - PeacefulSoul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接