|
| 1 | +#include "lualog.hpp" |
| 2 | + |
| 3 | +#include "thirdparty\easyloggingpp.h" |
| 4 | +#include <string> |
| 5 | + |
| 6 | +static int tocppstring(lua_State *L, std::string &logstr) { |
| 7 | + char pointer[20]; |
| 8 | + lua_Number tempd; |
| 9 | + int tempi; |
| 10 | + |
| 11 | + for (int i = 1; i <= lua_gettop(L); i++) { |
| 12 | + switch (lua_type(L, i)) { |
| 13 | + case LUA_TNIL: |
| 14 | + logstr.append("nil"); |
| 15 | + break; |
| 16 | + case LUA_TBOOLEAN: |
| 17 | + logstr.append(lua_toboolean(L, i) ? "true" : "false"); |
| 18 | + break; |
| 19 | + case LUA_TNUMBER: |
| 20 | + tempd = lua_tonumber(L, i); |
| 21 | + tempi = (int)tempd; |
| 22 | + if (tempi == tempd) |
| 23 | + logstr.append(std::to_string(tempi)); |
| 24 | + else |
| 25 | + logstr.append(std::to_string(tempd)); |
| 26 | + break; |
| 27 | + case LUA_TSTRING: |
| 28 | + logstr.append(lua_tostring(L, i)); |
| 29 | + break; |
| 30 | + default: |
| 31 | + if (luaL_callmeta(L, i, "__tostring")) { |
| 32 | + if (!lua_isstring(L, -1)) |
| 33 | + luaL_error(L, "'__tostring' must return a string"); |
| 34 | + logstr.append(lua_tostring(L, -1)); |
| 35 | + lua_pop(L, 1); |
| 36 | + } else { |
| 37 | + logstr.append(luaL_typename(L, i)); |
| 38 | + std::snprintf(pointer, 20, ": %p", lua_topointer(L, i)); |
| 39 | + logstr.append(pointer); |
| 40 | + } |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + logstr.append(", "); |
| 45 | + } |
| 46 | + |
| 47 | + if (!logstr.empty()) |
| 48 | + (logstr.pop_back(), logstr.pop_back()); |
| 49 | + |
| 50 | + return 0; |
| 51 | +} |
| 52 | + |
| 53 | +static int log_info(lua_State *L) { |
| 54 | + std::string logstr; |
| 55 | + tocppstring(L, logstr); |
| 56 | + LOG(INFO) << logstr; |
| 57 | + return 1; |
| 58 | +} |
| 59 | + |
| 60 | +static int log_warn(lua_State *L) { |
| 61 | + std::string logstr; |
| 62 | + tocppstring(L, logstr); |
| 63 | + LOG(WARNING) << logstr; |
| 64 | + return 1; |
| 65 | +} |
| 66 | + |
| 67 | +static int log_debug(lua_State *L) { |
| 68 | + std::string logstr; |
| 69 | + tocppstring(L, logstr); |
| 70 | + LOG(DEBUG) << logstr; |
| 71 | + return 1; |
| 72 | +} |
| 73 | + |
| 74 | +static int log_error(lua_State *L) { |
| 75 | + std::string logstr; |
| 76 | + tocppstring(L, logstr); |
| 77 | + LOG(ERROR) << logstr; |
| 78 | + return 1; |
| 79 | +} |
| 80 | + |
| 81 | +const luaL_Reg loglib[] = { |
| 82 | + {"info", log_info}, |
| 83 | + {"warn", log_warn}, |
| 84 | + {"debug", log_debug}, |
| 85 | + {"error", log_error}, |
| 86 | + |
| 87 | + {NULL, NULL} |
| 88 | +}; |
| 89 | + |
| 90 | +int luaopen_log(lua_State *L) { |
| 91 | + luaL_newlib(L, loglib); |
| 92 | + lua_pushcfunction(L, log_info); |
| 93 | + lua_setglobal(L, "print"); |
| 94 | + return 1; |
| 95 | +} |
0 commit comments