degesch: Lua: add a "buffer" property to servers

This commit is contained in:
Přemysl Eric Janouch 2015-11-24 21:42:08 +01:00
parent 0044672b85
commit 87e1236b30
1 changed files with 46 additions and 11 deletions

View File

@ -7446,6 +7446,19 @@ lua_server_gc (lua_State *L)
return 0;
}
static int
lua_server_get_buffer (lua_State *L)
{
struct lua_server *wrapper = luaL_checkudata (L, 1, XLUA_SERVER_METATABLE);
luaL_argcheck (L, wrapper->server, 1, "dead reference used");
if (wrapper->server->buffer)
lua_plugin_push_buffer (wrapper->plugin, wrapper->server->buffer);
else
lua_pushnil (L);
return 1;
}
static int
lua_server_send (lua_State *L)
{
@ -7461,6 +7474,7 @@ static luaL_Reg lua_server_table[] =
{
// TODO: some useful methods or values
{ "__gc", lua_server_gc },
{ "get_buffer", lua_server_get_buffer },
{ "send", lua_server_send },
{ NULL, NULL }
};
@ -7820,20 +7834,41 @@ lua_plugin_panic (lua_State *L)
return 0;
}
static int
lua_plugin_property_get (lua_State *L)
{
luaL_checktype (L, 1, LUA_TUSERDATA);
const char *property_name = luaL_checkstring (L, 2);
// Either it's directly present in the metatable
if (luaL_getmetafield (L, 1, property_name))
return 1;
// Or we try to find and eventually call a getter method
char *getter_name = xstrdup_printf ("get_%s", property_name);
bool found = luaL_getmetafield (L, 1, getter_name);
free (getter_name);
if (found)
{
lua_pushvalue (L, 1);
lua_call (L, 1, 1);
return 1;
}
return luaL_error (L, "%s: %s",
"no such method or property", property_name);
}
static void
lua_plugin_create_meta (lua_State *L, const char *name, luaL_Reg *fns)
{
luaL_newmetatable (L, name);
luaL_setfuncs (L, fns, 0);
// Otherwise any non-meta functions would be inaccessible
bool has_own_index = (lua_getfield (L, -1, "__index") != LUA_TNIL);
lua_pop (L, 1);
if (!has_own_index)
{
lua_pushvalue (L, -1);
// Emulate properties for convenience
lua_pushcfunction (L, lua_plugin_property_get);
lua_setfield (L, -2, "__index");
}
lua_pop (L, 1);
}