Trapping and handling errors.
Exercises, examples and other material relating to training module U111. This topic is presented on public courses Learning to program in Lua
, Lua Programming
, Lua Programming
|Articles and tips on this subject||updated|
|2360||Error Handling in Lua with assert and pcall|
When a function fails in lua, you'll often find that it return a nil value that you can check, or it returns two values, the second of which is an error status / message that tells you what went wrong.
Here's an example:
value = tonumber(stuff)
if value == nil then
|2706||Error trapping in Lua - no exceptions.|
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 ...
|2455||Lua examples - coroutines, error handling, objects, etc|
I have presented a bespoke Lua course over the last three days ... and it has lead me to some interesting new examples which I'm sharing here.
Object Orientation is more a way of thinking and coding than a language feature in Lua - when you set up a piece of data / structure / object, you do so in a ...
Examples from our training material
|errc|| Error handling on file open|
|gp0|| 'Control' for error trapping - failing example|
|gp1|| trapping an error via pcall|
|gp2|| Assert - test a condition and exit with your error if it fails|
|protectedcall|| pcall to trap errors in a lua function call|
|splot|| trapping Lua errors - nil and error|
|splut|| trapping Lua errors - assert|
|tbp|| Stack Traceback|
|wonky|| error checking through pcall|
Some modules are available for download
as a sample of our material or under an Open Training Notes License
for free download from http://www.training-notes.co.uk
Topics covered in this module
Logic, syntax, runtime.
Assert and Error functions.
Error Containment Functions such as pcall
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule
Well House Consultants specialise in training courses in
. We run
throughout the UK (and beyond for longer courses), and
at our training centre in Melksham, Wiltshire, England.
It's surprisingly cost effective to come on our public courses -
even if you live in a different
country or continent to us
We have a technical library of over 700 books on the subjects on which we teach.
These books are available for reference at our training centre. Also
available is the Opentalk
Forum for discussion of technical questions.