Lua error handling techniques

Lua is a powerful language, but with some flaws, among them, the fact that you can easily type something wrong, specially use lowercase or uppercase in the wrong places by accident, and it will silently introduce errors in your code.

Coroutines make it even more silent, when there is a error in a coroutine, the result is usually the coroutine just ending and leaving no error message behind. But all of this, has solutions.

First, many functions in Lua return error values, and a result value, most important in that is coroutine,resume(), that function returns a boolean value with the success (or not) and a error message if a error happened, using Lua feature of multiple return values.

Going along with that, we have the function “assert()” that stops execution if needed, and prints a error message, assert takes two arguments, one is a check, if it is false, the assert function stops execution, and prints the second argument to whatever place errors are being printed. Assert arguments and coroutine.resume() return values exactly allow you to do assert(coroutine.resume(coroutinename)).

Another interesting function is “pcall”, that means protected call, its first argument is a function handle, and the other arguments are the paremeters, a example would be ‘pcall(print, “hello world!”)’, and what this function do is ensure the program will continue running if whatever function you used on the first argument fails for whatever reason, if you DO want the program to spot and print a error message, pcall can also be used inside a assert, exactly like coroutine.resume.

What if you need to generate a error instead? One that will be caught by pcall or coroutine.resume? (or by your interpreter top level), for this we can use a function aptly named “error”, what it do is generate a error.

And a final issue, is that sometimes you want return values beside the failure, coroutine.resume in particular returns as second value a error message only upon failure of the code, but when it works, it will return whatever you wanted the coroutine it is resuming to return. Because of this, assert() and pcall() can pass along return values, since their first value will still be true or false for execution, you can use select to choose the other values, for example by doing this: