Lua Pcall Patterns
pcall is a function that runs another function and catches any error it raises. The program keeps running after a caught error.
pcall returns every result on success
The called function returns two values. pcall passes both back after true.
local function calc(a, b)
return a + b, a - b
end
local ok, sum, diff = pcall(calc, 10, 3)
print(ok, sum, diff)pcall in a loop keeps the good jobs
Each job runs under its own pcall. The loop counts successes and failures.
local jobs = {
function() return 5 end,
function() error("bad job") end,
function() return 9 end
}
local good = 0
local bad = 0
for i = 1, #jobs do
local ok = pcall(jobs[i])
if ok then
good = good + 1
else
bad = bad + 1
end
end
print(good, bad)pcall around a whole stage catches a mid-stage failure
The stage adds numbers and then fails. The pcall catches the failure and the program moves on.
local function stage()
local total = 10 + 5
error("stage broke")
return total
end
local ok = pcall(stage)
print(ok)
print("next stage ran")Example
local tasks = {
function() return 4 end,
function() error("oops") end,
function() return 6 end,
function() error("again") end
}
local sum = 0
local failed = 0
for i = 1, #tasks do
local ok, value = pcall(tasks[i])
if ok then
sum = sum + value
else
failed = failed + 1
end
end
print(sum, failed)
print("done")Key points
- Return on success: pcall returns true followed by every value the called function returns.
- Return on failure: pcall returns false followed by the error value.
- No stop: a failed pcall does not stop the program, so later code still runs.
- Loop use: pcall inside a loop lets one bad job fail while the other jobs still run.
- Whole stage: pcall can wrap a whole stage, so a failure inside any step is caught in one place.
In this example, four tasks run in a loop under pcall. The two successes add 4 and 6 to the sum, the two failures raise the failure count, and the final line proves the program ran to the end.
Note
pcall never raises an error itself, even when the function it runs fails.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does pcall return when the called function returns 8 and 3?