如何打印出错误信息?

在名为 Roblox studio 的软件中,我需要帮助编写脚本,使得在游戏中出现错误时,能够使用普通的打印功能再次输出错误信息,就像这个示例一样:

Local error = —-不管发生了什么错误

Print(error) —- 然后简单地将其打印出来
点赞
用户13955436
用户13955436

使用 io 库中的 stderr 流来打印调试信息。

-- 基于 print 定义调试函数
function debug(...) io.stderr:write(table.concat({...}, '\9') .. '\n') end

-- Debug 函数和普通的 “print()” 函数一样, 但它会写入到 stderr 流而不是 stdout 流
debug('[filename.lua]', 'debug')

使用 "error()" 函数来打印错误信息。

if true then
    error("It should not be true!")
end

如果想要从函数中捕获错误,使用 xpcall()

-- 定义 debug 函数
function debug(...) io.stderr:write(table.concat({...}, '\9') .. '\n') end

xpcall(
    function()
        local b = {}
        -- 由于无法引用 nil 值,该语句将抛出错误
        print(a.b)
    end,
    function(err)
        debug('[xpcall]', err)
    end
)

xpcall() 在出现错误时不会停止执行,因此只需在运行时捕捉任何意外错误时将代码封装在其中即可。

2020-10-08 22:30:22
用户2860267
用户2860267

Roblox提供了几种不同的方式来跟踪脚本和本地脚本中抛出错误的情况。

如果您想在本地脚本中观察错误,并且您知道特定的代码块可能会抛出错误,您可以使用pcall()作为try-catch块。

local success, result = pcall(function()
    error("this is a test error message")
end)
if not success then
    print("An error was thrown!")
    print(result) --"this is a test error message"
end

如果您想在所有脚本中观察错误,可以将回调附加到ScriptContext.Error信号。该信号在抛出任何错误时触发。它提供有关错误的信息,包括消息、调用堆栈和抛出错误的脚本的引用。

警告ScriptContext.Error仅在注册它的脚本的上下文中触发。脚本只会观察服务器脚本中抛出的错误,在LocalScript中注册只会观察客户端抛出的错误。

local ScriptContext = game:GetService("ScriptContext")
ScriptContext.Error:Connect( function(message, stack, context)
    print("An error was thrown!")
    print("Message : ", message)
    print("Stack : ", stack)
    print("Context :", context:GetFullName())
end)

类似地,如果您只关心错误消息本身,您也可以观察它们被打印到输出窗口,使用LogService.MessageOut信号。该信号在输出任何内容时触发。包括消息、警告和错误。

local LogService = game:GetService("LogService")
LogService.MessageOut:Connect( function(message, messageType)
    if messageType == Enum.MessageType.MessageError then
        print("An error was thrown!")
        print(message)
    end
end)
2020-10-08 22:35:20