src/lua_objs.c
changeset 93 42ade8285570
child 94 05a96b200d7b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/lua_objs.c	Tue Mar 31 19:35:51 2009 +0300
@@ -0,0 +1,83 @@
+#include "lua_objs.h"
+
+#include <lua5.1/lua.h>
+#include <lua5.1/lualib.h>
+#include <lua5.1/lauxlib.h>
+
+/**
+ * Our lua wrapper for irc_net
+ */
+struct lua_irc_net {
+    struct irc_net *net;
+};
+
+/**
+ * Wrapper for irc_client
+ */
+struct lua_client {
+    struct irc_client *client;
+};
+
+static int lua_client_quit (lua_State *L)
+{
+    struct lua_client *lua_client;
+    err_t err;
+   
+    // validate the lua_client arg
+    if ((lua_client = luaL_checkudata(L, 1, "evirc.client")) == NULL)
+        return luaL_argerror(L, 1, "`client` expected");
+    
+    // the message
+    const char *message = luaL_checkstring(L, 2);
+
+    // execute
+    if ((err = irc_client_quit(lua_client->client, message)))
+        return luaL_error(L, "irc_client_quit: %s", error_name(err));
+
+    // ok
+    return 0;
+}
+
+static const struct luaL_Reg lua_client_lib[] = {
+    {   "quit",     &lua_client_quit    },
+    {   NULL,       NULL                    }
+};
+
+/**
+ * Initializes a lua_irc_client wrapper for the given client in the give lua state. This registers a set of globals for
+ * 'client' and 'networks'.
+ */
+static err_t lua_client_init (lua_State *L, struct irc_client *client)
+{
+    // allocate the global "client" object
+    // XXX: mem errors?
+    struct lua_client *lua_client = lua_newuserdata(L, sizeof(*client));
+    
+    // push a new metatable to identify the client object
+    luaL_newmetatable(L, "evirc.client");
+
+    // set the metatable __index to itself
+    lua_pushvalue(L, -1);
+    lua_setfield(L, -1, "__index");
+
+    // register the methods to the metatable
+    luaL_register(L, NULL, lua_client_lib);
+
+    // set the client userdata's metatable
+    lua_setmetatable(L, -2);
+
+    // initialize it
+    lua_client->client = client;
+
+    // store it as a global
+    lua_setglobal(L, "client");
+
+    // ok
+    return SUCCESS;
+}
+
+err_t lua_objs_init (lua_State *L, struct nexus *nexus)
+{
+    // init the various bits
+    return lua_client_init(L, nexus->client);
+}