Error Handling in Lua with assert and pcall
Archive - Originally posted on "The Horse's Mouth" - 2009-08-13 17:46:29 - Graham Ellis
Here's an example:
value = tonumber(stuff)
if value == nil then
print ("Nah!")
else
print ("That is half of ",value * 2)
end
(full source of example)
You can reduce the code somewhat by using the built in assert function to check, generate the message, and exit with a full stack trace - example:
io.write ("How many bits: ")
val2 = tonumber(io.read())
assert(val2 >= 1,"need to have at least one piece")
(full source code of example)
There are times when a lua function will generate an error before it returns to the calling code .. but you want to trap that .. and you can do so via pcall or protected call. Example:
goodun,eachlen = pcall(cutter,val1,val2)
This calls the cutter function with two parameters, and the result is returned into eachlen. The other return variable is a status to tell you whether or not the function worked.
(full source code of example)
Illustration - during a private Lua course at a customer's office. As well as private training courses on site, we run public Lua courses at our Melksham, Wiltshire, UK training centre. See [here].