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

我正在尝试将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

我已经在互联网上搜寻了很长时间,但是找不到解决方法。

点赞
用户65863
用户65863

lua_pushcfunction()函数接受一个C风格的函数指针。_不带捕获_的lambda可以转换为这样的函数指针,但_带捕获_的lambda则不能。

使用lua_pushcclosure() 1代替。它允许您关联用户定义的值(称为upvalues)与C函数,例如您的“this”指针,或者只是一个指向DrawList的指针等。

当创建C函数时,可以将一些值与之关联,从而创建一个C闭包(参见§3.4); 每当调用该函数时,这些值就可以被访问。要将值与C函数关联起来,首先应该将这些值推入堆栈中(当有多个值时,先推入第一个值)。然后调用lua_pushcclosure来创建并将C函数推入堆栈,参数n用于告诉函数应该关联多少个值。lua_pushcclosure还将这些值从堆栈中弹出。

1:lua_pushcfunction()仅是具有0个upvalue定义的lua_pushcclosure()的包装器。

例如:

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

    // 使用pThis->DrawList等等...

    return 0;
};

...

lua_State* L = luaL_newstate();
...
//lua_pushcfunction(L, addToDrawList);
lua_pushlightuserdata(L, this);
lua_pushcclosure(L, addToDrawList, 1);
...
2020-04-07 01:38:31