如果我理解正确的话,默认情况下,当出现错误时,Lua会调用调试库"debug.traceback“。
但是,在将Lua嵌入到C代码中时,如下面的示例所示:Simple Lua API Example
我们只在堆栈顶部提供了错误消息。
即
if (status) {
/* If something went wrong, error message is at the top of */
/* the stack */
fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
/* I want to print a stacktrace here. How do I do that? */
exit(1);
}如何在初始错误后从C打印堆栈跟踪?
发布于 2013-05-02 01:41:06
根据Nicol上面的答案工作是一个有效的例子:
static int traceback(lua_State *L) {
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
lua_getfield(L, -1, "traceback");
lua_pushvalue(L, 1);
lua_pushinteger(L, 2);
lua_call(L, 2, 1);
fprintf(stderr, "%s\n", lua_tostring(L, -1));
return 1;
}
int main(int argc, char **argv) {
lua_State *L = lua_open();
luaL_openlibs(L);
lua_pushcfunction(L, traceback);
int rv = luaL_loadfile(L, "src/main.lua");
if (rv) {
fprintf(stderr, "%s\n", lua_tostring(L, -1));
return rv;
} else {
return lua_pcall(L, 0, 0, lua_gettop(L) - 1);
}
}发布于 2015-09-16 17:10:42
我遇到了和你一样的问题,我发现这样做是可行的:
luaL_traceback(L, L, NULL, 1);
printf("%s\n", lua_tostring(L, -1));因为luaL_traceback是用来打印堆栈的debug.traceback(),所以我认为这可能是一种合适的方式,你可以阅读luaL_traceback的API手册或只是阅读Lua的源代码来弄清楚参数的含义。
发布于 2014-04-14 02:48:30
mxcl的代码有一些问题:
static int traceback(lua_State *L) {
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
lua_getfield(L, -1, "traceback");
//---------------------------
lua_pop(L,-2); //to popup the 'debug'
//---------------------------
lua_pushvalue(L, 1);
lua_pushinteger(L, 2);
lua_call(L, 2, 1);
fprintf(stderr, "%s\n", lua_tostring(L, -1));
return 1;
}https://stackoverflow.com/questions/12256455
复制相似问题