c++ - 如何通过 lightuserdata 对象将表参数从 lua 传递到 C++?

标签 c++ lua

我已经注册了一个函数,它创建了一个供 C++ 和 lua 使用的 lightuserdata。当我使用简单变量、整数和字符串进行测试时,该部分工作正常。当它是字符串和整数时,我可以在 lua 中创建我的 lightuserdata 而不会出错。然而,当我尝试使用表格时,它变得更加复杂

std::string aString = lua_tostring(lua,-4);

第一个参数是正确的,因为它应该是一个字符串

if (lua_type(lua,-3 == LUA_TTABLE))  //is true so i know it recognizes it as a table
{
    auto t = lua_gettable(lua, -3);

    size_t tableLen = lua_rawlen(lua, -3); // also gives me the correct size
    lua_settop(lua, 1); //this discards the rest right? which i don't want.
    //luaL_checktype(lua, 1, LUA_TTABLE); //using this crashes the application expecting
// table but getting string
    lua_getfield(lua, 1, "a");
    lua_getfield(lua, 1, "b");
    lua_getfield(lua, 1, "c");
    lua_getfield(lua, 1, "d");
    lua_getfield(lua, 1, "e");
    std::cout << lua_gettop(lua) << std::endl; //after using the getfields i get the new table size 
//correctly (i assume, it turns 1 more value than expected, i think it's the table itself.
    //int a = luaL_checkinteger(lua, -5); //these don't work as they expect numbers but get nil
    //int b = luaL_checkinteger(lua, -4);
    //int c = luaL_checkinteger(lua, -3);
    //int d = luaL_checkinteger(lua, -2);
    //int e = luaL_checkinteger(lua, -1);
    std::cout << lua_tointeger(lua, -2) << std::endl; //returns always 0

}

尝试忽略该表并获取堆栈的其余部分会给我 0x000000 上的违规错误,尽管第三个值按预期正确调试,第四个为空,即使我不这样做它也正确通过了不要使用表格。

我正在尝试做的可能是这样吗?

任何对正确方向的评论将不胜感激。 另外,如果我不知道表中键的名称,我应该使用什么?

最佳答案

if (lua_type(lua,-3 == LUA_TTABLE)) //is true so i know it recognizes it as a table

这里有很大错误,或者你没有发布实际代码。

您不是在检查索引 -3 下的值的类型,而是在询问索引 false 下的值的类型,因为 -3 == LUA_TTABLE 显然是 false

“检查”之后发生的任何崩溃都是此错误的结果。它会将任何不是 nil 的内容识别为表格。

关于c++ - 如何通过 lightuserdata 对象将表参数从 lua 传递到 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54850543/

相关文章:

c++ - 与在构造函数中将非常量左值绑定(bind)到右值相关的错误

c++ - 如何使用实体/组件/系统架构在更多数据驱动的环境中设置 openGL?

lua - ServiceStack Redis,如何将Lua表返回为List

c++ - Sfinae on 具有零或一个参数的函数

c++ - 将一个 va_list 作为参数传递给另一个

c++ - 如何在自己的方法中使用 lambda 表达式

c++ - 如何像构造函数初始化 C++ 中的所有类对象一样初始化 C 中结构中的所有对象?

algorithm - 如何计算二次贝塞尔曲线和水平线之间的交点?

c++ - Luabind:std::map 的 return_STL_iterator

c++ - 嵌入 LuaJIT - 创建包含文件夹