将 Lua 表从 C++ 传递到 .路亚脚本

passing a lua table from C++ to .Lua script

本文关键字:脚本 Lua 表从 C++      更新时间:2023-10-16

我花了 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: %sn", lua_tostring(L, -1));
         exit(1);
}

所以我得到了那个错误:运行脚本失败:尝试调用表值

请注意,该文件还有其他几个我从 c++ 成功调用的函数。

有人可以帮我解决这个错误吗? 这可能是来自 LUA 的错误吗? cz 我非常正确地遵循了这些步骤...我想!

该函数必须在堆栈上的第一个,在 args 之前。

您可以:

  1. 在生成表之前推送函数以调用堆栈,例如:

    lua_getglobal(L, "MTable");
    ...generate table on stack...
    int result = lua_pcall(L, 1, 0, 0);
    
  2. 按照您现在执行的顺序执行,然后在执行 pcall 之前交换 arg 和函数:

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