Pass a Lua function to a std::function with Swig

Let's assume for sake of simplicity, a std::function<void()> written in Lua has to be passed down from your script back into your C++ engine.

First be sure to place the lua_fnptr module of Swig in your .i file

%include "lua_fnptr.i"

Next provide a wrapper class

class LuaFnPtr {
        LuaFnPtr(SWIGLUA_REF fn) : fn(fn) {};
        void operator()() {
                lua_call(this->fn.L, 0, 0);
        SWIGLUA_REF fn;

Now you can wrap some callback function right away, e.g.:

void addListener(const char *event, SWIGLUA_REF callback)
        LuaFnPtr lua_fn_ptr(callback);
        self->addListener(event, lua_fn_ptr);

void addListener(const char *event, std::function<void()> f) ...