问题描述
如果我理解正确的话,Lua 默认会在发生错误时调用调试库debug.traceback".
If I understand this correctly, Lua by default will call the debug library "debug.traceback" when an error occurs.
然而,当像这里的例子那样将 Lua 嵌入到 C 代码中时:简单的 Lua API 示例
However, when embedding Lua into C code like done in the example here: Simple Lua API Example
我们只有栈顶的错误信息可用.
We only have available the error message on the top of the stack.
即
if (status) {
/* If something went wrong, error message is at the top of */
/* the stack */
fprintf(stderr, "Couldn't load file: %s
", lua_tostring(L, -1));
/* I want to print a stacktrace here. How do I do that? */
exit(1);
}
如何在初始错误后从 C 打印堆栈跟踪?
How do I print the stack trace from C after the initial error?
推荐答案
Lua 默认会在发生错误时调用调试库debug.traceback".
Lua by default will call the debug library "debug.traceback" when an error occurs.
不,不会.Lua runtime (lua.exe) 会做到这一点,但 Lua 库不会自己做到这一点.如果您想要一个包含 Lua 错误的调用堆栈,那么您需要生成一个.
No, it won't. The Lua runtime (lua.exe) will do that, but the Lua library will not do that on its own. If you want a call-stack with your Lua errors, then you need to generate one.
Lua 运行时使用 lua_pcall
's 误差函数.调用错误函数时堆栈尚未展开,因此您可以在那里获得堆栈跟踪.运行时使用的错误函数是这个:
The Lua runtime does this by using lua_pcall
's error function. The stack has not been unwound when the error function is called, so you can get a stack trace there. The error function the runtime uses is this one:
static int traceback (lua_State *L) {
if (!lua_isstring(L, 1)) /* 'message' not a string? */
return 1; /* keep it intact */
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return 1;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1); /* pass error message */
lua_pushinteger(L, 2); /* skip this function and traceback */
lua_call(L, 2, 1); /* call debug.traceback */
return 1;
}
这篇关于从带有嵌入式 lua 的 C 代码打印堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论