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.
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.
We define a
mayError
function that simply raises an error.In the
main
function, we usepcall
to callmayError
.pcall
returns two values:status
: a boolean indicating whether the call was successfulerr
: the error message if an error occurred, or nil if successful
We check the
status
. If it’s false, we know an error occurred, and we print the error message.The code after the
pcall
will always execute, even ifmayError
raised an error.
When you run this program, you’ll see:
This demonstrates how we can recover from errors in Lua using pcall
, allowing our program to continue execution even when errors occur.