How do you throw Lua error up?

Puddler picture Puddler · Mar 2, 2016 · Viewed 13k times · Source

Is it possible to throw a Lua error from a function to be handled by the script calling the function?

For example the following will throw an error at indicated comment

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

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

But what I would rather do is catch the error and throw out a custom error by the function caller

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 

The intention being that in my actual use cases my functions would be more complicated and I would like to provide more meaningful error messages

Answer

Puddler picture Puddler · Mar 3, 2016

The stack level of an error can be specified when throwing a new error

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.

Using the example given in the question

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