From 1e0d828c687c71e419d4bfea9d53aebeba16607b Mon Sep 17 00:00:00 2001 From: buffet Date: Thu, 2 Jan 2020 22:15:00 +0000 Subject: [PATCH] Make event handler registration generic --- include/luak/luak.h | 1 + kiwmi/luak/kiwmi_server.c | 26 +------------------------- kiwmi/luak/luak.c | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+), 25 deletions(-) diff --git a/include/luak/luak.h b/include/luak/luak.h index 08ee890..0bf7d22 100644 --- a/include/luak/luak.h +++ b/include/luak/luak.h @@ -19,6 +19,7 @@ struct kiwmi_lua { struct wl_list callbacks; // lua_callback::link }; +int luaK_callback_register_dispatch(lua_State *L); struct kiwmi_lua *luaK_create(struct kiwmi_server *server); bool luaK_dofile(struct kiwmi_lua *lua, const char *config_path); void luaK_destroy(struct kiwmi_lua *lua); diff --git a/kiwmi/luak/kiwmi_server.c b/kiwmi/luak/kiwmi_server.c index fae0772..d9c74c0 100644 --- a/kiwmi/luak/kiwmi_server.c +++ b/kiwmi/luak/kiwmi_server.c @@ -18,30 +18,6 @@ #include "luak/kiwmi_view.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 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[] = { - {"on", l_kiwmi_server_on}, + {"on", luaK_callback_register_dispatch}, {"quit", l_kiwmi_server_quit}, {"view_under_cursor", l_kiwmi_server_view_under_cursor}, {NULL, NULL}, diff --git a/kiwmi/luak/luak.c b/kiwmi/luak/luak.c index 7392dfd..face428 100644 --- a/kiwmi/luak/luak.c +++ b/kiwmi/luak/luak.c @@ -17,6 +17,32 @@ #include "luak/kiwmi_server.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 * luaK_create(struct kiwmi_server *server) {