将Lua表从C ++传递到.Lua脚本 [英] passing a lua table from C++ to .Lua script

查看:132
本文介绍了将Lua表从C ++传递到.Lua脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去6个小时我一直在努力解决这个问题!而且我无法到达任何地方:s

I have spent the past 6 hours trying to solve this ! and i coulnt get anywhere :s

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

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:

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

所以现在我将表放在堆栈的顶部. 我已经通过书面证明了这一点: if(lua_istable(L,lua_gettop(L)))`返回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.

然后我这样做了:

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

请注意,该文件还有其他一些我正在c ++中成功调用的功能.

Kindly note that the file has several other functions that i am calling successfully from c++.

有人可以帮助我解决此错误吗?这可以是LUA的错误吗? cz我非常正确地按照了步骤进行操作...我猜!

can somebody please help me solve this error ? can this be a bug from LUA? cz i followed the steps very correctly...i guess !

推荐答案

该函数必须在args之前在栈中 first .

The function has to be first on the stack, before the args.

您可以:

  1. 在生成表之前将函数推入堆栈,例如:

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

  • 按您现在的顺序执行,然后在执行pcall之前交换arg和函数:

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

  • 这篇关于将Lua表从C ++传递到.Lua脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆