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

回眸只為那壹抹淺笑 提交于 2020-01-05 06:44:33

问题


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);
}


来源:https://stackoverflow.com/questions/51063716/how-to-get-returned-table-from-lua-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!