0Pricing
Lua Academy · Lesson

Protected Calls with pcall

Catch errors safely using pcall and interpret return values.

pcall Basics

pcall(f, ...) calls function f with arguments ... in protected mode. If f succeeds, pcall returns true followed by all return values. If f errors, pcall returns false followed by the error message. The program continues either way.

local function risky(x)
  if x < 0 then error("negative input: " .. x) end
  return math.sqrt(x)
end

local ok, result = pcall(risky, 9)
print(ok, result)    -- true  3.0

ok, result = pcall(risky, -1)
print(ok, result)    -- false  ...: negative input: -1

Catching Specific Errors

Check the error value type after pcall to handle different error kinds differently. Table errors have structured data; string errors have a message. Always handle both cases.

local function op(errType)
  if errType == "table" then
    error({code=42, msg="structured error"})
  else
    error("plain string error")
  end
end

local ok, err = pcall(op, "table")
if not ok then
  if type(err) == "table" then
    print("Code:", err.code, "Msg:", err.msg)
  else
    print("String error:", err)
  end
end

All lessons in this course

  1. The error() Function
  2. Protected Calls with pcall
  3. xpcall and Message Handlers
  4. Structured Error Objects
← Back to Lua Academy