如何从 C++ 中监听 Lua 中的特定函数调用?
How to listen to specific function call in Lua from C++?
假设我有以下 Lua 代码。
function touched(x, y)
end
function moved(x, y)
end
function released(x, y)
end
这些函数是用 lua_pcall
从 C++ 调用的,所以我也可以在 C++ 中收听这些事件。
但我想知道是否可以添加一个侦听器来侦听基于 C++ 中特定 Lua 函数的名称的侦听器。
比如在C++中可以是这样的
lua_addlistener(L, "touched", this, &MyClass::touchedFromLua);
然后可以监听Lua代码中的touched
函数。 (如果函数 "touched" 存在)
是否可以做类似的事情?
您可以用自己的函数替换该函数,然后在该函数中处理监听器后调用原始函数:
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;
}
假设我有以下 Lua 代码。
function touched(x, y)
end
function moved(x, y)
end
function released(x, y)
end
这些函数是用 lua_pcall
从 C++ 调用的,所以我也可以在 C++ 中收听这些事件。
但我想知道是否可以添加一个侦听器来侦听基于 C++ 中特定 Lua 函数的名称的侦听器。
比如在C++中可以是这样的
lua_addlistener(L, "touched", this, &MyClass::touchedFromLua);
然后可以监听Lua代码中的touched
函数。 (如果函数 "touched" 存在)
是否可以做类似的事情?
您可以用自己的函数替换该函数,然后在该函数中处理监听器后调用原始函数:
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;
}