Lua C代码中如何打印完整的堆栈跟踪?
- 内容介绍
- 文章标签
- 相关推荐
本文共计320个文字,预计阅读时间需要2分钟。
如果我在Lua中遇到错误,Lua默认会在发生错误时调用调试库`debug.traceback`。然而,当Lua被嵌入到C代码中时,例如以下示例所示:
Simple Lua API Example我们只能在堆栈顶部提供错误信息。
即:
luaif (status) then /...
如果我明白这一点,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打印堆栈跟踪?
Lua by default will call the debug library “debug.traceback” when an error occurs.
不,不会. Lua运行时(lua.exe)将会这样做,但Lua库不会自己做.如果您想要使用Lua错误的调用堆栈,则需要生成一个.
Lua运行时通过使用lua_pcall‘s错误功能执行此操作.当调用错误函数时,堆栈没有被解开,所以可以在那里获取堆栈跟踪.运行时使用的错误功能是这样的:
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; }
本文共计320个文字,预计阅读时间需要2分钟。
如果我在Lua中遇到错误,Lua默认会在发生错误时调用调试库`debug.traceback`。然而,当Lua被嵌入到C代码中时,例如以下示例所示:
Simple Lua API Example我们只能在堆栈顶部提供错误信息。
即:
luaif (status) then /...
如果我明白这一点,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打印堆栈跟踪?
Lua by default will call the debug library “debug.traceback” when an error occurs.
不,不会. Lua运行时(lua.exe)将会这样做,但Lua库不会自己做.如果您想要使用Lua错误的调用堆栈,则需要生成一个.
Lua运行时通过使用lua_pcall‘s错误功能执行此操作.当调用错误函数时,堆栈没有被解开,所以可以在那里获取堆栈跟踪.运行时使用的错误功能是这样的:
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; }

