Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从C++;?_C++_Lua_Listener - Fatal编程技术网

C++ 如何从C++;?

C++ 如何从C++;?,c++,lua,listener,C++,Lua,Listener,假设我有下面的Lua代码 function touched(x, y) end function moved(x, y) end function released(x, y) end 这些函数从C++调用,使用 LuaAupLea>代码>,所以我也可以在C++中侦听这些事件。 但是我想知道是否可以添加一个侦听器,它根据C++中的函数名来侦听特定的Lua函数。 例如,在C中,它可以是如下所示++ lua\u addlistener(L,“touch”,this,&MyClass::touche

假设我有下面的Lua代码

function touched(x, y)
end
function moved(x, y)
end
function released(x, y)
end

这些函数从C++调用,使用<代码> LuaAupLea>代码>,所以我也可以在C++中侦听这些事件。 <>但是我想知道是否可以添加一个侦听器,它根据C++中的函数名来侦听特定的Lua函数。 例如,在C中,它可以是如下所示++

lua\u addlistener(L,“touch”,this,&MyClass::touchedFromLua)

然后,它可以收听Lua代码中的
触摸式
功能。(如果存在“触摸”功能)


这是否可以执行类似的操作?

您可以用自己的函数替换该函数,然后在处理侦听器后在该函数中调用原始函数:

lua_getglobal(L, "touched");
lua_pushlightuserdata(L, this);
lua_pushcclosure(L, &MyClass::touchedFromLua, 2); 
//add  original function and this as upvalues
lua_setglobal(L, "touched");
touchedFromLua必须是静态的,并且看起来像:

int MyClass::touchedFromLua(Lua_State *L){
    int args = lua_gettop(L);
    MyClass* thiz = std::reinterpret_cast<MyClass*>(lua_touserdata(lua_upvalueindex(2)));
    thiz->touchedFromLua_nonstatic(L);

    lua_pushvalue(lua_upvalueindex(1));
    lua_insert(L, 1);
    lua_call(L, args , LUA_MULTRET);
    int rets = lua_gettop(L);
    return rets;
}
int MyClass::touchedFromLua(Lua_状态*L){
int args=lua_gettop(L);
MyClass*thiz=std::重新解释(lua_-tuserdata(lua_-upvalueindex(2));
thiz->从Lua_非静态(L)触摸;
lua_pushvalue(lua_upvalueindex(1));
lua_插入物(L,1);
lua_call(L,args,lua_MULTRET);
int-rets=lua_gettop(L);
返回rets;
}

也许您可以利用观察者模式?查看此帖子了解更多详细信息。
lua\u-toserdata
返回
void*
,因此
static\u-cast
应该足够了。不需要重新解释(顺便说一句,这不在
std
名称空间中)。