Recover in Lua

In Lua, we can implement error handling and recovery using protected calls with pcall. This is similar to the concept of recover in other languages.

-- This function may raise an error
local function mayError()
    error("a problem")
end

-- Main function
local function main()
    -- pcall is used to catch any errors that occur in the function
    local status, err = pcall(function()
        mayError()
    end)

    -- If an error occurred, status will be false and err will contain the error message
    if not status then
        print("Recovered. Error:\n", err)
    end

    -- This code will run, because pcall catches the error
    print("After mayError()")
end

main()

In this example, we use Lua’s pcall function to create a protected call. This is similar to using recover in a deferred function in other languages.

  1. We define a mayError function that simply raises an error.

  2. In the main function, we use pcall to call mayError. pcall returns two values:

    • status: a boolean indicating whether the call was successful
    • err: the error message if an error occurred, or nil if successful
  3. We check the status. If it’s false, we know an error occurred, and we print the error message.

  4. The code after the pcall will always execute, even if mayError raised an error.

When you run this program, you’ll see:

$ lua recover.lua
Recovered. Error:
    a problem
After mayError()

This demonstrates how we can recover from errors in Lua using pcall, allowing our program to continue execution even when errors occur.