将带子表的表传递给Lua函数(来自C++)

我正在尝试将带有子表的表作为参数从C++传递给Lua函数。

以下是我的代码,虽然无法工作,但显示了我正在尝试的内容。

    class DragInfo{
    public:
        std::vector <std::string> files;
        glm::vec2 position;
    };

    //一个回调函数,将DragInfo作为带有两个子表的表传递给Lua函数
    void callDragged(DragInfo &info)
    {
        lua_getglobal(L, "dragged");
        if (!lua_isfunction(L, -1))
        {
            lua_pop(L, 1);
            return;
        }
        lua_newtable(L);
        for (size_t i = 0; i < info.files.size(); ++i)
        {
            lua_pushinteger(L, static_cast<lua_Integer>(i + 1));
            lua_pushstring(L, info.files[i].c_str());
            lua_settable(L, -3);
        }
        lua_pushnumber(L, static_cast<lua_Number>(info.position.x));
        lua_setfield(L, -2, "x");
        lua_pushnumber(L, static_cast<lua_Number>(info.position.y));
        lua_setfield(L, -2, "y");

        if (lua_pcall(L, 1, 0, 0))
            std::cout << "错误:" <<  lua_tostring(L, -1) << std::endl;
    }

在Lua中,例如我想能够...

function dragged(info)
   for i=1, #info.files do
       print("拖动的文件名:" .. info.files[i])
   end
   print("拖动的位置:" .. info.position.x .. " " .. info.position.y)
end

结果可能如下所示

拖动的文件名:background.jpg
拖动的文件名:apple.png
拖动的位置:425 32

我应该如何修改我的C++函数以使其像示例一样正常工作?

点赞
用户1944004
用户1944004

它非常简单。只需创建子表并将其分配给最外层表中的字段。

我还建议,如果“ dragged”不是函数,则引发错误,而不是什么也不做。

// 将DragInfo传递给Lua函数作为具有2个子表的表
void callDragged(DragInfo&info) {
    lua_getglobal(L,“ dragged”);
    if(!lua_isfunction(L,-1)){
        lua_pop(L,1);
        lua_pushstring(L,“参数不是函数”);
        lua_error(L);
        返回;
    }

    //最外层表
    lua_newtable(L);

    //子表“文件”
    lua_newtable(L);
    for(size_t i = 0; i <info.files.size(); ++ i){
        lua_pushinteger(L,i + 1);
        lua_pushstring(L,info.files [i] .c_str());
        lua_settable(L,-3);
    }
    lua_setfield(L,-2,“ files”);

    //子表“位置”
    lua_newtable(L);
    lua_pushnumber(L,info.position.x);
    lua_setfield(L,-2,“ x”);
    lua_pushnumber(L,info.position.y);
    lua_setfield(L,-2,“ y”);
    lua_setfield(L,-2,“位置”);

    如果(lua_pcall(L,1,0,0)!= 0){
        std::cout <<“错误:”<< lua_tostring(L,-1)<< '\ n';
        lua_pop(L,1);
    }
}
2018-07-08 09:45:40