c++ - 如何在与LUA脚本一起使用的Lambda中引用 'this'

标签 c++ lua

我试图将LUA API添加到我的C++程序中,并且试图允许该脚本绘制到我的GUI中。到目前为止,我的lambda函数具有以下功能:

auto addToDrawList = [](lua_State* L) -> int
{
    int DrawType = (int)lua_tonumber(L, -2);
    std::string Label = (std::string)lua_tostring(L, -1);

    bool found = false;
    for (int i = 0; i <= DrawList.size(); i++)
    {
        if (DrawList[i].Active == false && !found)
        {
            switch (DrawType)
            {
            case(0):
                break;
            case(1):
                DrawList[i].Active = true;
                DrawList[i].DrawType = Type::TextBox;
                DrawList[i].Label = Label;
                break;
            }
            found = true;
        }
    }

    return 0;
};

这是我正在运行的LUA脚本:
const char* LUA_FILE = R"(
    addToDrawList(1, "Test")
)";

这就是我将函数推送到LUA堆栈的方式:
lua_State* L = luaL_newstate();

lua_newtable(L);
int uiTableInd = lua_gettop(L);
lua_pushvalue(L, uiTableInd);
lua_setglobal(L, "Ui");

lua_pushcfunction(L, addToDrawList);
lua_setfield(L, -2, "addToDrawList");

问题出在我的第一个脚本中,因为它无法到达this内部的“DrawList”数组。

因此,为解决此问题,我尝试通过执行以下操作将this添加到lambda的捕获列表中:
auto addToDrawList = [this](lua_State* L) -> int

似乎可以解决该错误,但是最后一个脚本出现了问题:
lua_pushcfunction(L, addToDrawList);

Error

我一直在Internet上搜索修复程序,但是找不到。

最佳答案

lua_pushcfunction()采用C样式的函数指针。无需捕获的lambda可以转换为这样的函数指针,但是不能捕获。

请改用 lua_pushcclosure() 1。它将允许您将用户定义的值(称为upvalues)与C函数相关联,例如this指针或仅指向DrawList的指针等。

When a C function is created, it is possible to associate some values with it, thus creating a C closure (see §3.4); these values are then accessible to the function whenever it is called. To associate values with a C function, first these values should be pushed onto the stack (when there are multiple values, the first value is pushed first). Then lua_pushcclosure is called to create and push the C function onto the stack, with the argument n telling how many values should be associated with the function. lua_pushcclosure also pops these values from the stack.



1:lua_pushcfunction()只是lua_pushcclosure()的包装,定义了0个upvalue。

例如:

auto addToDrawList = [](lua_State* L) -> int
{
    const MyClassType *pThis = (const MyClassType*) lua_topointer(L, lua_upvalueindex(1));

    // use pThis->DrawList as needed...

    return 0;
};

...

lua_State* L = luaL_newstate();
...
//lua_pushcfunction(L, addToDrawList);
lua_pushlightuserdata(L, this);
lua_pushcclosure(L, addToDrawList, 1);
...

关于c++ - 如何在与LUA脚本一起使用的Lambda中引用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61071267/

相关文章:

c - lua从c api检查堆栈上的表

c++ - 如何使用 ClangCodeModel 插件在 QtCreator 中设置 C++ 标准?

C++ SEH - EXCEPTION_DISPOSITION 枚举和 __except() 过滤器表达式之间的相关性

c++ - 使用 C++ std::list 迭代器替换列表中的项目

hash - Lua:将表中的每个新元素设置为默认值

lua - 如何处理 Wireshark Lua 解剖器中的位字段?

function - Lua中的方法声明

c++ - 将 double 传递给程序中的稍后部分 - 使用对话框输入

c++ - 没有类减法运算符重载但仍然有效

ios - 使用 LUA 的 Cocos2dx iOS 项目