Panic in Lua
Our program demonstrates how to handle exceptional situations in Lua. While Lua doesn’t have a built-in panic
function like some other languages, we can simulate similar behavior using error handling and the error
function.
Running this program will cause it to raise an error, print an error message, and exit with a non-zero status.
When the first error()
in main
is called, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first error()
call.
Note that unlike some languages which use exceptions for handling of many errors, in Lua it is idiomatic to use multiple return values to indicate errors, with the first return value typically being nil
or false
in case of an error, and the second value being the error message.
The pcall
function (protected call) is used to catch any errors that might occur during the execution of a function. It’s similar to a try-catch block in other languages.