aboutsummaryrefslogtreecommitdiff
path: root/src/lua/log.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lua/log.c')
-rw-r--r--src/lua/log.c33
1 files changed, 24 insertions, 9 deletions
diff --git a/src/lua/log.c b/src/lua/log.c
index d02775c..4bf4e16 100644
--- a/src/lua/log.c
+++ b/src/lua/log.c
@@ -4,8 +4,20 @@
#include "api.h"
#include "../any_log.h"
+static lua_CFunction lua_log_stringformat = NULL;
+
static int lua_log_format(lua_State *state, any_log_level_t level) {
- const char *value = luaL_checkstring(state, 1);
+
+ // Use string.format to print safely
+ //
+ int n_args = lua_gettop(state);
+ lua_pushcfunction(state, lua_log_stringformat);
+
+ for (int i = 1; i <= n_args; ++i)
+ lua_pushvalue(state, i);
+
+ lua_call(state, n_args, 1);
+ const char *message = lua_tostring(state, -1);
lua_getglobal(state, "debug");
lua_getfield(state, -1, "getinfo");
@@ -15,8 +27,8 @@ static int lua_log_format(lua_State *state, any_log_level_t level) {
// S: source, l: currentline, n: name
lua_pushstring(state, "Sln");
- const char *source = "x", *func = "y";
- char buffer[4096] = { 0 };
+ const char *source = "?", *func = "?";
+ char buffer[4096];
if (lua_pcall(state, 2, 1, 0) == LUA_OK) {
@@ -33,18 +45,15 @@ static int lua_log_format(lua_State *state, any_log_level_t level) {
snprintf(buffer, sizeof(buffer), "lua %s:%d", shortsrc, line);
}
- source = buffer;
-
lua_getfield(state, -3, "name");
const char *name = lua_tostring(state, -1);
- func = name == NULL
- ? "..."
- : name;
+ source = buffer;
+ func = name ? name : "...";
}
lua_pop(state, 3);
- any_log_format(level, source, func, "%s", value);
+ any_log_format(level, source, func, "%s", message);
return 0;
}
@@ -92,6 +101,12 @@ int lua_log_library(lua_State *state)
{ "trace", lua_log_trace },
{ NULL, NULL },
};
+
+ lua_getglobal(state, "string");
+ lua_getfield(state, -1, "format");
+ lua_log_stringformat = lua_tocfunction(state, -1);
+ lua_pop(state, 2);
+
luaL_newlib(state, library);
return 1;
}