How do I improve the error logging to include line numbers? This is for an internal error that's thrown as I'm reading a Lua file. The only error message I get is attempt to index a function value, no line number or filename.
void handleLuaError(lua_State* L, const char* msg, const char* filename) {
handleError("%s %s: %s", msg, filename, lua_tostring(luaState, -1));
lua_pop(L, 1);
luaL_traceback (L, L, msg, 2);
char* result = 0;
if (lua_isstring(L, -1)) result = strdup_s(lua_tostring(L, -1));
lua_pop(L, 1);
SPDLOG_WARN("traceback: {}", result);
}
void readLua(const char *filename) {
SPDLOG_INFO("readLua {}", filename);
if (luaL_loadfile(luaState, filename) || lua_pcall(luaState, 0, 0, 0)) {
handleLuaError(luaState, "Reading file", filename);
}
}
I tried adding luaL_traceback, as you can see, but the only message I get from luaL_traceback is stack traceback:, no actual traceback. I read that lua_pcall can trash the stack, and that I need to do some debug logging when the error happens, such as in an error handler, and not after lua_pcall has returned. Someone suggested I need to use xpcall and provide a custom error handler, but I can't find any documentation or example code on how to call xpcall in C++.
How do I set a custom error handler? Or is there a way to just tell Lua to put more info in internal errors? When I see my particular error message in other people's StackOverflow posts, the error message (attempt to index ...) shows filename and line number, so it should be possible to get filename and line number with this error.
Here's the Lua file which is causing the error:
addAchievement({
code = "AchNewCity",
name = "A New City",
text = "Welcome to NewCity. " ..
"Your first task is to " ..
"build some roads. Click " ..
"on the Transportation Tool in the " ..
"bottom left corner.",
condition = "true",
effect = "FRoadTool,FRoadStreet",
hint = ""
});