Codectionary / Developer documentation / Lua

Lua pcall

pcall calls a function in protected mode. On success it returns true followed by the function’s return values. On failure it returns false and the error object, allowing the caller to decide what to do next. It does not undo changes made before the error.

Syntax

local ok, result = pcall(function()
  return risky_work()
end)

Examples

Handle an invalid input

Pass the function itself to pcall, followed by its arguments. The first call prints 12; the second prints Not a valid quantity.

local function parse_quantity(text)
  local number = tonumber(text)
  if not number then error("Expected a number") end
  return number
end

for _, input in ipairs({ "12", "oops" }) do
  local ok, result = pcall(parse_quantity, input)
  if ok then
    print(result)
  else
    print("Not a valid quantity")
  end
end

A false result is not a failed call

The function returns normally with false and a reason. pcall adds true in front: execution succeeded even though the business result was false.

local function can_enter()
  return false, "Ticket required"
end

local ok, allowed, reason = pcall(can_enter)
print(ok)      -- true
print(allowed) -- false
print(reason)  -- Ticket required

Best practices

  • Use pcall(work, argument), not pcall(work(argument)); the latter evaluates work before the protected call begins.
  • Check the first return value before interpreting the remaining values. An error object is not necessarily a string.
  • Handle or report failures at a meaningful boundary. Wrapping everything in pcall and ignoring errors can hide bugs.
  • Use xpcall with a message handler when you need a traceback; pcall alone does not produce one.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading