How to get returned table from Lua function in C++

2019-08-14 07:34发布

问题:

I'm trying to figure out how to get the returned table from the Lua function in C++.

My code:

if (lua_pcall(L, 0, 1, 0)) {
        std::cout << "ERROR : " << lua_tostring(L, -1) << std::endl;
}
vector<float> vec;

if (lua_istable(L, -1) { 

    //how to copy table to vec?
}

How can I copy the returned table to vector if the table size is unknown? Thanks!

回答1:

I think I found out how to do it using lua_next.

lua_getglobal(L, name);

if (lua_pcall(L, 0, 1, 0)) {
        std::cout << "ERROR : " << lua_tostring(L, -1) << std::endl;
}
vector<float> vec;

if (lua_istable(L, -1) { 

   lua_pushvalue(L, -1);
   lua_pushnil(L);

   while (lua_next(L, -2))
   {

        if (lua_isnumber(L, -1))
        {
            vec.push_back(lua_tonumber(L, -1));
        }
        lua_pop(L, 1);
    }
    lua_pop(L, 1);
}