Error handling 你是如何抛出错误的?
是否可能从要由调用函数的脚本处理的函数中抛出Lua错误 例如,以下内容将在指定的注释处引发错误Error handling 你是如何抛出错误的?,error-handling,lua,throw,Error Handling,Lua,Throw,是否可能从要由调用函数的脚本处理的函数中抛出Lua错误 例如,以下内容将在指定的注释处引发错误 local function aSimpleFunction(...) string.format(...) -- Error is indicated to be here end aSimpleFunction("An example function: %i",nil) 但我更愿意做的是捕获错误并由函数调用方抛出自定义错误 local function aSimpleFunction
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
这样做的目的是,在我的实际用例中,我的功能将更加复杂,我希望提供更有意义的错误消息,使用
捕捉错误就像使用
pcall
My_Error()
--Error Somehow
end
local success,err = pcall(My_Error)
if not success then
error(err)
end
毫无疑问,你在问这是怎么回事。那么pcall
在受保护的线程(受保护的调用)中运行一个函数,如果它成功运行,则返回一个bool和一个值(返回的内容/错误)
也不要认为这意味着函数的参数是不可能的,只需将它们传递给pcall
:
My_Error(x)
print(x)
--Error Somehow
end
local success,err = pcall(My_Error, "hi")
if not success then
error(err)
end
有关更多错误处理控制的信息,请参阅和在抛出新错误时可以指定错误的堆栈级别
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
通常,error会在消息开头添加一些有关错误位置的信息。level参数指定如何获取错误位置。对于级别1(默认值),错误位置是调用错误函数的位置。级别2将错误指向调用调用错误的函数的位置;等等传递级别0可避免向消息中添加错误位置信息
使用问题中给出的示例
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
@汤姆布卢吉特,回答吧?;)@PaulKulchenko-似乎写评论而不是回答的想法很有感染力;-)@我注意到埃戈尔斯克里普图诺夫;)@PaulKulchenko我宁愿删除这个问题也不愿写一个答案。但是,我确实想帮助询问者了解易懂的文档(Lua参考手册就是这样)是一个主要参考。我不认为这个问题和对它的任何直接回答对其他人有帮助。如果问题的范围更广,那么他们就会更广泛。
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