【发布时间】:2025-12-23 09:15:17
【问题描述】:
是否可以从函数中抛出 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
目的是在我的实际用例中我的功能会更复杂,我想提供更有意义的错误消息
【问题讨论】:
-
@TomBlodget,让它成为答案? ;)
-
@PaulKulchenko - 似乎写 cmets 而不是答案的想法很有感染力 ;-)
-
@EgorSkriptunoff,我注意到了 ;)
-
@PaulKulchenko 我宁愿看到这个问题被删除而不是写一个答案。但是,我确实想帮助提问者了解可理解的文档(Lua 参考手册是)是主要参考。我不认为这个问题及其任何直接答案对其他人有帮助。如果问题更广泛,那么他们会。
标签: error-handling lua throw