implement lua_log and lua_log_level
authorTero Marttila <terom@fixme.fi>
Wed, 01 Apr 2009 00:38:16 +0300
changeset 104 fc196bb4bcc2
parent 103 454aea1e4f11
child 105 b6b183fbf373
implement lua_log and lua_log_level
src/log.c
src/log.h
src/lua_objs.c
--- a/src/log.c	Wed Apr 01 00:27:39 2009 +0300
+++ b/src/log.c	Wed Apr 01 00:38:16 2009 +0300
@@ -9,6 +9,18 @@
  */
 static enum log_level _log_level = LOG_LEVEL_DEFAULT;
 
+/**
+ * List of log level names
+ */
+const char *log_level_names[] = {
+    "DEBUG",
+    "INFO",
+    "WARN",
+    "ERROR",
+    "FATAL",
+    NULL
+};
+
 #define _LOG_LEVEL_NAME(ll) case LOG_ ## ll: return #ll;
 const char *log_level_name (enum log_level level)
 {
--- a/src/log.h	Wed Apr 01 00:27:39 2009 +0300
+++ b/src/log.h	Wed Apr 01 00:38:16 2009 +0300
@@ -21,6 +21,11 @@
 };
 
 /**
+ * List of log_level values as strings, NULL-terminated
+ */
+extern const char *log_level_names[];
+
+/**
  * The default log level
  */
 #define LOG_LEVEL_DEFAULT LOG_INFO
--- a/src/lua_objs.c	Wed Apr 01 00:27:39 2009 +0300
+++ b/src/lua_objs.c	Wed Apr 01 00:38:16 2009 +0300
@@ -1,4 +1,5 @@
 #include "lua_objs.h"
+#include "log.h"
 
 #include <string.h>
 
@@ -516,6 +517,55 @@
 }
 
 /**
+ * Global functions
+ */
+static int lua_log_level (lua_State *L)
+{
+    // log level as a string
+    enum log_level new_level = luaL_checkoption(L, 1, NULL, log_level_names);
+
+    // set it
+    set_log_level(new_level);
+
+    // ok
+    return 0;
+}
+
+static int lua_log (lua_State *L)
+{
+    // log level as a string
+    enum log_level level = luaL_checkoption(L, 1, NULL, log_level_names);
+    
+    // log message
+    const char *msg = luaL_checkstring(L, 2);
+
+    // log it
+    log_msg(level, "lua", "%s", msg);
+
+    // ok
+    return 0;
+}
+
+static const struct luaL_Reg lua_global_functions[] = {
+    {   "log_level",    &lua_log_level              },
+    {   "log",          &lua_log                    },
+    {   NULL,           NULL                        }
+};
+
+static void lua_global_init (lua_State *L)
+{
+    const struct luaL_Reg *reg;
+
+    for (reg = lua_global_functions; reg->name && reg->func; reg++) {
+        // put the function on the stack
+        lua_pushcfunction(L, reg->func);
+
+        // set the global
+        lua_setglobal(L, reg->name);
+    }
+}
+
+/**
  * Set up the lua state in protected mode
  */
 static int _lua_objs_init (lua_State *L)
@@ -527,6 +577,7 @@
         luaL_error(L, "lua_touserdata: NULL");
 
     // init the various bits
+    lua_global_init(L);
     lua_nexus_init(L, nexus);
     lua_modules_init(L, nexus->modules);
     lua_module_init(L);