Main Content

Error trapping in Lua - no exceptions.

Archive - Originally posted on "The Horse's Mouth" - 2010-04-04 01:58:50 - Graham Ellis

Lua's a small language - it's about a twentieth of the size of most of the others I teach - so there isn't the space for the nicities of things like expection handling. But it does very nicely, thank you!

Functions return nil (false) values if they fail, and true values (even 0 is true in Lua, which is rather clever!) if they work - that's easy enough to check for.

And if you're concerned that a function may fail catastrophically in mid operation, you can simply wrap it in a call to pcall. The syntax may look a bit odd - but it works like magic, returning a true vaue if it works, and a false if it fails ...

... and your result come back as a second parameter.

Icing on the cake - you get the error message back as the second parameter if the first is false. Neat!

See a source example [here]