gpt4 book ai didi

error-handling - 您如何抛出Lua错误?

转载 作者:行者123 更新时间:2023-12-03 07:38:00 25 4
gpt4 key购买 nike

是否可以从调用该函数的脚本处理的函数中引发Lua错误?

例如,以下内容将在指定的注释处引发错误

local function aSimpleFunction(...)
string.format(...) -- Error is indicated to be here
end

aSimpleFunction("An example function: %i",nil)

但是我更愿意做的是捕获错误并由函数调用者抛出一个自定义错误
local function aSimpleFunction(...)
if pcall(function(...)
string.format(...)
end) == false then
-- I want to throw a custom error to whatever is making the call to this function
end

end

aSimpleFunction("An example function: %i",nil) -- Want the error to start unwinding here

目的是在我的实际用例中,我的功能会更复杂,并且我想提供更有意义的错误消息

最佳答案

抛出新错误时可以指定错误的堆栈级别

error("Error Message") -- Throws at the current stack
error("Error Message",2) -- Throws to the caller
error("Error Message",3) -- Throws to the caller after that

Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.



使用问题中给出的示例
local function aSimpleFunction(...)
if pcall(function(...)
string.format(...)
end) == false then
error("Function cannot format text",2)
end

end

aSimpleFunction("An example function: %i",nil) --Error appears here

关于error-handling - 您如何抛出Lua错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35735857/

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