简体   繁体   English

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

[英]passing a lua table from C++ to .Lua script

I have spent the past 6 hours trying to solve this ! 我花了过去6个小时来解决这个问题! and i coulnt get anywhere :s 而且我无法到达任何地方:s

I want to be able to create a lua table in a c++ file and then pass that to a lua script file, which has the following lua function: 我希望能够在c ++文件中创建lua表,然后将其传递给lua脚本文件,该文件具有以下lua函数:

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

i dynamically created a one dimensional array with two strings: 我动态创建了一个带有两个字符串的一维数组:

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

so now i have the table on top of the stack. 所以现在我把桌子放在栈顶了。 I have verified it by writting this : if( lua_istable(L,lua_gettop(L)))` which returned 1, which means it is a table. 我已经通过写这个来验证它:if(lua_istable(L,lua_gettop(L)))`返回1,这意味着它是一个表。

then I did this: 然后我这样做:

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

so I got that error: Failed to run script: attempt to call a table value 所以我得到了这个错误: 无法运行脚本:尝试调用表值

Kindly note that the file has several other functions that i am calling successfully from c++. 请注意,该文件还有其他几个我正在c ++中成功调用的功能。

can somebody please help me solve this error ? 有人可以帮我解决这个错误吗? can this be a bug from LUA? 这可以是LUA的错误吗? cz i followed the steps very correctly...i guess ! 我非常正确地遵循了步骤...我猜!

The function has to be first on the stack, before the args. 该函数必须在堆栈上,然后在args之前。

You can either: 您可以:

  1. push the function to call on the stack before generating the table, eg: 在生成表之前将函数推入堆栈,例如:

     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: 按照您现在执行的顺序进行操作,然后在执行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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM