gpt4 book ai didi

lua - 获取 lua pcall 中错误的真实堆栈跟踪

转载 作者:行者123 更新时间:2023-12-02 06:55:04 30 4
gpt4 key购买 nike

所以对于我的 pcall 语句,我一直在做这样的事情

local status, err = pcall(fn)
if not status then
print(err)
print(debug.stacktrace())
end

这对于一些基本的东西来说效果很好,但问题是 debug.stacktrace() 返回当前的相对堆栈跟踪,而不是错误的堆栈跟踪。如果 fn 中的错误发生在堆栈中的下 10 层,那么我不知道它到底发生在哪里,只是这个 pcall block 失败了。我想知道是否有办法获取 pcall 的堆栈跟踪而不是当前的堆栈跟踪。我尝试了 debug.stacktrace(err) 但没有什么区别。

最佳答案

您需要使用xpcall 提供一个自定义函数,将堆栈跟踪添加到错误消息中。 From PiL :

Frequently, when an error happens, we want more debug information than only the location where the error occurred. At least, we want a traceback, showing the complete stack of calls leading to the error. When pcall returns its error message, it destroys part of the stack (the part that went from it to the error point). Consequently, if we want a traceback, we must build it before pcall returns. To do that, Lua provides the xpcall function. Besides the function to be called, it receives a second argument, an error handler function. In case of errors, Lua calls that error handler before the stack unwinds, so that it can use the debug library to gather any extra information it wants about the error.

您可能想检查这个patch that extends pcall to include stacktrace .

按照评论中的建议,您可以使用 local ok, res = xpcall(f, debug.traceback, args...) 与 Lua 5.2+ 或 LuaJIT(打开 Lua 5.2 兼容性) )并使用了上面提到的 Lua 5.1 补丁。

关于lua - 获取 lua pcall 中错误的真实堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45788739/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com