Errors in Lua

In Lua, error handling is typically done through the use of the error() function and pcall() (protected call) function. Unlike Go, Lua doesn’t have a built-in error type or a convention for multiple return values. Instead, we’ll use Lua’s idiomatic approach to error handling.

-- In Lua, we don't need to import packages like in Go.
-- We'll define our functions directly.

-- This function demonstrates basic error handling in Lua
function f(arg)
    if arg == 42 then
        -- In Lua, we use the error() function to raise an error
        error("can't work with 42")
    end
    -- If there's no error, we just return the result
    return arg + 3
end

-- In Lua, we don't have predefined error variables.
-- Instead, we can use strings or tables as error objects.
local ErrOutOfTea = "no more tea available"
local ErrPower = "can't boil water"

function makeTea(arg)
    if arg == 2 then
        return ErrOutOfTea
    elseif arg == 4 then
        -- In Lua, we can concatenate strings to add context
        return "making tea: " .. ErrPower
    end
    return nil -- nil indicates no error in Lua
end

-- Main function to demonstrate error handling
function main()
    -- Demonstrate f function
    for _, i in ipairs({7, 42}) do
        -- In Lua, we use pcall for protected calls
        local success, result = pcall(f, i)
        if not success then
            print("f failed:", result)
        else
            print("f worked:", result)
        end
    end

    -- Demonstrate makeTea function
    for i = 1, 5 do
        local err = makeTea(i)
        if err then
            -- In Lua, we compare strings directly
            if err == ErrOutOfTea then
                print("We should buy new tea!")
            elseif string.find(err, ErrPower) then
                print("Now it is dark.")
            else
                print("unknown error: " .. err)
            end
        else
            print("Tea is ready!")
        end
    end
end

-- Call the main function
main()

To run this Lua script, save it as errors.lua and execute it with the Lua interpreter:

$ lua errors.lua
f worked: 10
f failed: can't work with 42
Tea is ready!
Tea is ready!
We should buy new tea!
Tea is ready!
Now it is dark.

In this Lua version:

  1. We use the error() function to raise errors, similar to errors.New() in Go.
  2. We use pcall() for protected calls, which is similar to Go’s error checking.
  3. Instead of nil for no error, we return nil explicitly in Lua.
  4. We use string comparison for error checking, as Lua doesn’t have a dedicated error type.
  5. We use string concatenation (..) for adding context to errors, similar to wrapping errors in Go.

While Lua’s error handling is less structured than Go’s, it still allows for effective error management and propagation through the use of error() and pcall().