diff options
| author | Federico Angelilli <code@fedang.net> | 2025-04-13 03:37:01 +0200 |
|---|---|---|
| committer | Federico Angelilli <code@fedang.net> | 2025-04-13 03:37:01 +0200 |
| commit | 0aed18911e27b80a4dbe1a252f9485382a4073c7 (patch) | |
| tree | 5bdc87cb223c7f812a672bda88be1fd2020b1516 /src/lua | |
| parent | 91149e6c41a094bf29ed6a1aa00c0fa6c1015a24 (diff) | |
Handle formatted string in log
Diffstat (limited to 'src/lua')
| -rw-r--r-- | src/lua/log.c | 33 |
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; } |
