error and pcall
Sometimes a program cannot continue. A number is zero when you need to divide by it, or a value is missing. Lua has two tools for these cases: error to report a problem, and pcall to catch it.
error: stop and report
error(message) stops the program and shows the message:
function divide(a, b)
if b == 0 then
error("cannot divide by zero")
end
return a / b
end
print(divide(10, 2))
print(divide(7, 0))
print("never reached")
Output:
5.0
/usr/bin/lua5.4: main.lua:3: cannot divide by zero
The first call worked and printed 5.0. The second call stopped the whole program, so the last print never ran. Lua added main.lua:3: to the message: the file name and the line where error was called. This helps you find the problem.
Stopping with a clear message is better than going on with a wrong value. Use error when a function cannot do what it was asked.
pcall: catch the error
pcall means protected call. It runs a function for you. If the function raises an error, the program does not stop. Instead, pcall returns the error as a value.
function divide(a, b)
if b == 0 then
error("cannot divide by zero")
end
return a / b
end
local ok, result = pcall(divide, 10, 2)
print(ok, result)
local ok2, err = pcall(divide, 7, 0)
print(ok2, err)
print("still running")
Output:
true 5.0
false main.lua:3: cannot divide by zero
still running
You pass the function first, then its arguments: pcall(divide, 10, 2) runs divide(10, 2). pcall returns two values. On success, they are true and the function's result. On an error, they are false and the error message. Check the first value with if to know which case you are in.
Only the message
To get the message without the file and line, pass 0 as a second argument to error:
function divide(a, b)
if b == 0 then
error("cannot divide by zero", 0)
end
return a / b
end
print(pcall(divide, 7, 0))
Output:
false cannot divide by zero
This is better when you show the message to a user.
Use pcall only where you can do something useful with the error, like printing a friendly message or using a default value.
In the exercise, call divide with pcall and print either the result or the error message.