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

时间:2019-02-24 09:34:17

标签: 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上给我一个违反错误,尽管第3个值正确地调试为应该是的,第4个为空,即使如果我不正确它也会正确通过不要使用表格。

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

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

1 个答案:

答案 0 :(得分:1)

  

如果(lua_type(lua,-3 == LUA_TTABLE))//是true,那么我知道它将其识别为表

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

您不是要检查索引-3下的值的类型,而是要查询索引false下的值的类型,因为-3 == LUA_TTABLE显然是false。 / p>

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