Rob Norris
Wrap any Lua function with a sigc++ slot
I’m slightly concerned that I wrote this without really thinking about it.
class LuaSlot {
public:
static inline sigc::slot<void> Wrap(lua_State *l) {
lua_getfield(l, LUA_REGISTRYINDEX, "_slot");
if (lua_isnil(l, -1)) {
lua_newtable(l);
lua_pushvalue(l, -1);
lua_setfield(l, LUA_REGISTRYINDEX, "_slot");
}
lua_pushvalue(l, -2);
int ref = luaL_ref(l, -2);
lua_pop(l, 1);
return sigc::bind(sigc::ptr_fun(&trampoline), l, ref);
}
private:
static inline void trampoline(lua_State *l, int ref) {
lua_getfield(l, LUA_REGISTRYINDEX, "_slot");
lua_rawgeti(l, -1, ref);
luaL_unref(l, -2, ref);
lua_remove(l, -2);
lua_call(l, -1, 0);
}
};