在前面那篇文章Lua的基本信息调试(二)中,我使用了lua_getstack(L, 2, &debug);去取堆栈中的错误信息,但至于错误信息在stack中的层数并不清楚,经过信息打印发现,错误信息在stack的最深处,因此,修改函数为:
int pcall_callback_err_fun(lua_State* L)
{
lua_Debug debug;
//取得层数
uint32_t level = 0;
while (lua_getstack(L, level, &debug)) {
level++;
}
if (!level) {
return 0;
}
lua_getstack(L, level, &debug);
lua_getinfo(L, "Sln", &debug);
std::string err = lua_tostring(L, -1);
lua_pop(L, 1);
std::stringstream msg;
msg << debug.short_src << ":line " << debug.currentline;
if (debug.name != 0) {
msg << "(" << debug.namewhat << " " << debug.name << ")";
}
msg << " [" << err << "]";
lua_pushstring(L, msg.str().c_str());
return 1;
}
这样我们就能准确的获得lua脚本在运行中的错误信息!
本文介绍了如何在Lua中使用lua_getstack和lua_getinfo来精确获取错误堆栈信息,特别是在处理脚本错误时,通过遍历堆栈找到最底层的错误位置,结合源文件、行号和函数名生成详细的错误提示,从而有效定位和解决lua运行时的问题。
--lua_getstack&spm=1001.2101.3001.5002&articleId=6208505&d=1&t=3&u=ad8e862a01964746854aaf94f92f6fff)
1万+

被折叠的 条评论
为什么被折叠?



