您如何抛出Lua错误?

Pud*_*ler 4 error-handling lua throw

是否可以从函数抛出Lua错误,以由调用该函数的脚本来处理?

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

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

aSimpleFunction("An example function: %i",nil)
Run Code Online (Sandbox Code Playgroud)

但是我想做的是捕获错误并通过函数调用者抛出自定义错误

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 
Run Code Online (Sandbox Code Playgroud)

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

Pud*_*ler 8

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

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
Run Code Online (Sandbox Code Playgroud)

通常,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 
Run Code Online (Sandbox Code Playgroud)


Col*_*Two 5

使用error功能

error("something went wrong!")
Run Code Online (Sandbox Code Playgroud)