如何将 Lua 中的表格传递到 C++ 中?

我该如何将一个未知长度的 Lua 表格传递到绑定的 C++ 函数中?

我希望能够像这样调用 Lua 函数:

call_C_Func({1,1,2,3,5,8,13,21})

并将表格内容复制到一个数组中(最好是 STL 向量)?

原文链接 https://stackoverflow.com/questions/2219669

点赞
stackoverflow用户233522
stackoverflow用户233522

如果你使用 LuaBind ,那么只需要一个注册的调用就可以了。如果你想自己编写代码,需要查看 lua_next 函数。

基本上代码如下:

lua_pushnil(state); // 第一个键
index = lua_gettop(state);
while ( lua_next(state,index) ) { // 遍历键
  something = lua_tosomething(state,-1); // 例如 tonumber
  results.push_back(something);
  lua_pop(state,1); // 恢复栈
}
2010-02-08 05:33:26
stackoverflow用户15795
stackoverflow用户15795

你还可以使用 lua_objlen

返回给定可接受索引处值的“长度”: 对于字符串,这是字符串的长度; 对于表,这是长度运算符('#')的结果; 对于用户数据,这是为用户数据分配的内存块的大小; 对于其他值,它为 0。

2010-02-08 15:10:46
stackoverflow用户199201
stackoverflow用户199201
这是我的尝试(没有错误检查):

int lua_test(lua_State * L){
    std :: vector < int > v;
    const int len = lua_objlen(L,-1);
    forint i = 1; i <= len; ++ i){
        lua_pushinteger(L,i);
        lua_gettable(L,-2);
        v.push_back(lua_tointeger(L,-1));
        lua_pop(L,1);
    }
    forint i = 0; i <len; ++ i){
        std :: cout << v [i] << std :: endl;
    }
    返回0;
}
2010-02-12 15:15:49