Make event handler registration generic

This commit is contained in:
buffet 2020-01-02 22:15:00 +00:00
parent 15c70816f3
commit 3ac3781e9f
3 changed files with 28 additions and 25 deletions

View file

@ -19,6 +19,7 @@ struct kiwmi_lua {
struct wl_list callbacks; // lua_callback::link struct wl_list callbacks; // lua_callback::link
}; };
int luaK_callback_register_dispatch(lua_State *L);
struct kiwmi_lua *luaK_create(struct kiwmi_server *server); struct kiwmi_lua *luaK_create(struct kiwmi_server *server);
bool luaK_dofile(struct kiwmi_lua *lua, const char *config_path); bool luaK_dofile(struct kiwmi_lua *lua, const char *config_path);
void luaK_destroy(struct kiwmi_lua *lua); void luaK_destroy(struct kiwmi_lua *lua);

View file

@ -18,30 +18,6 @@
#include "luak/kiwmi_view.h" #include "luak/kiwmi_view.h"
#include "server.h" #include "server.h"
static int
l_kiwmi_server_on(lua_State *L)
{
luaL_checkudata(L, 1, "kiwmi_server"); // server
luaL_checktype(L, 2, LUA_TSTRING); // type
luaL_checktype(L, 3, LUA_TFUNCTION); // callback
lua_getmetatable(L, 1);
lua_getfield(L, -1, "__events");
lua_pushvalue(L, 2);
lua_gettable(L, -2);
luaL_argcheck(L, lua_iscfunction(L, -1), 2, "invalid event");
lua_pushvalue(L, 1);
lua_pushvalue(L, 3);
if (lua_pcall(L, 2, 1, 0)) {
wlr_log(WLR_ERROR, "%s", lua_tostring(L, -1));
return 0;
}
return 1;
}
static int static int
l_kiwmi_server_quit(lua_State *L) l_kiwmi_server_quit(lua_State *L)
{ {
@ -88,7 +64,7 @@ l_kiwmi_server_view_under_cursor(lua_State *L)
} }
static const luaL_Reg kiwmi_server_methods[] = { static const luaL_Reg kiwmi_server_methods[] = {
{"on", l_kiwmi_server_on}, {"on", luaK_callback_register_dispatch},
{"quit", l_kiwmi_server_quit}, {"quit", l_kiwmi_server_quit},
{"view_under_cursor", l_kiwmi_server_view_under_cursor}, {"view_under_cursor", l_kiwmi_server_view_under_cursor},
{NULL, NULL}, {NULL, NULL},

View file

@ -17,6 +17,32 @@
#include "luak/kiwmi_server.h" #include "luak/kiwmi_server.h"
#include "luak/kiwmi_view.h" #include "luak/kiwmi_view.h"
int
luaK_callback_register_dispatch(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA); // server
luaL_checktype(L, 2, LUA_TSTRING); // type
luaL_checktype(L, 3, LUA_TFUNCTION); // callback
int has_mt = lua_getmetatable(L, 1);
luaL_argcheck(L, has_mt, 1, "no metatable");
lua_getfield(L, -1, "__events");
luaL_argcheck(L, lua_istable(L, -1), 1, "no __events");
lua_pushvalue(L, 2);
lua_gettable(L, -2);
luaL_argcheck(L, lua_iscfunction(L, -1), 2, "invalid event");
lua_pushvalue(L, 1);
lua_pushvalue(L, 3);
if (lua_pcall(L, 2, 1, 0)) {
wlr_log(WLR_ERROR, "%s", lua_tostring(L, -1));
return 0;
}
return 1;
}
struct kiwmi_lua * struct kiwmi_lua *
luaK_create(struct kiwmi_server *server) luaK_create(struct kiwmi_server *server)
{ {