简体   繁体   中英

How to pass a table parameter from lua to C++ through a lightuserdata object?

I have registered a function that creates a lightuserdata to be used by C++ and lua. that part is working fine when I tested using simple variables, ints and strings. I can create my lightuserdata in lua without errors when it's strings and ints. however when I try to use tables it gets more complicated

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

first parameter being correct as it is supposed to be a string

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

}

Trying to ignore the table and get the rest of the stack gives me an violation error on 0x000000, though the 3rd value debugs correctly as what is supposed to be and the 4th is empty, even though it passes correctly if i don't use table.

is What I'm trying to do possible proceeding like this?

any comment to the right direction would be appreciated. also, what should I use if I don't know the name of the key in the table?

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

Big error here, or you didn't post the actual code.

You're not checking the type of the value under index -3, you're asking the type of the value under index false , since -3 == LUA_TTABLE is clearly false .

Whatever crash that happens after that "check" - is a result of this error. It will recognize as a table anything that is not nil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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