1

Let's say I have the following Lua code.

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

These functions are called from C++ with lua_pcall so I can also listen to these events in C++.

But I wonder if it's possible to add a listener that listens to specific Lua function based on the name of that function in C++.

For example, it can be something like the following in C++

lua_addlistener(L, "touched", this, &MyClass::touchedFromLua);

And then it can listen to the touched function in Lua code. (if the function "touched" exists)

Is this possible to do something similar?

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • 1
    Maybe you can utilize an observer pattern? Check this [SO](https://stackoverflow.com/questions/27249195/implementing-c-to-lua-observer-pattern) post for more details. – kingJulian Jul 10 '18 at 10:32

1 Answers1

1

You can replace the function with your own and then in that function call the original after you handled the listener:

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 would have to be static and look something like:

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;
}
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • 1
    `lua_touserdata` returns `void *`, so `static_cast` should be sufficient. No need for `reinterpret_cast` (which is, by the way, not in the `std` namespace). – Henri Menke Jul 10 '18 at 21:18