我试图将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);
我一直在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 argumentn
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/