Protected Calls with pcall()
Part of the Logic & Flow section of Coddy's Lua journey — lesson 33 of 54.
While error() stops your program when something goes wrong, sometimes you want to handle errors without crashing. Lua's pcall() function lets you safely execute code that might fail.
The name pcall() stands for "protected call." It wraps a function call in a protective layer that catches any errors. Instead of your program crashing, pcall() returns information about what happened.
Here's the basic syntax:
local status, result = pcall(functionName, arg1, arg2)The pcall() function returns two values. The first is a boolean status: true if the function succeeded, or false if an error occurred. The second value depends on the status—if successful, it's the function's return value; if there was an error, it's the error message.
Here's a practical example:
function divide(a, b)
if b == 0 then
error("Cannot divide by zero")
end
return a / b
end
local success, result = pcall(divide, 10, 0)
if success then
print("Result: " .. result)
else
print("Error caught: " .. result)
endIn this example, the division by zero triggers an error, but instead of crashing, pcall() catches it. The program continues running and can handle the error gracefully by checking the status value.
Challenge
EasyWrite a function safeCalculate that takes operation, a, and b and returns the result of the calculation or an error message.
The function should use pcall() to safely perform the requested mathematical operation. Create an inner function that performs the calculation based on the operation string, then wrap it with pcall() to catch any errors.
Logic:
- Create an inner function that checks the operation type and performs the calculation
- For "add", return
a + b - For "subtract", return
a - b - For "multiply", return
a * b - For "divide", check if
bis 0 and callerror("Division by zero")if true, otherwise returna / b - For any other operation, call
error("Invalid operation") - Use
pcall()to execute the inner function - If successful, return
"Result: "followed by the result - If an error occurs, return
"Error: "followed by the error message
Parameters:
operation(string): The operation to perform ("add", "subtract", "multiply", or "divide")a(number): The first operandb(number): The second operand
Returns: A string containing either "Result: " followed by the calculation result, or "Error: " followed by the error message (string)
Cheat sheet
The pcall() function (protected call) allows you to safely execute code that might fail without crashing your program.
Basic syntax:
local status, result = pcall(functionName, arg1, arg2)pcall() returns two values:
- status:
trueif the function succeeded,falseif an error occurred - result: The function's return value if successful, or the error message if an error occurred
Example:
function divide(a, b)
if b == 0 then
error("Cannot divide by zero")
end
return a / b
end
local success, result = pcall(divide, 10, 0)
if success then
print("Result: " .. result)
else
print("Error caught: " .. result)
endThis catches the error instead of crashing, allowing the program to continue and handle the error gracefully.
Try it yourself
function safeCalculate(operation, a, b)
-- Write code here
end
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board