Skip to content
Lua

Tratamento de Erros (pcall)

Chamadas protegidas e tratamento de erros em Lua.

#error#pcall#exception

Code

lua
-- Function that may error
local function risky(x)
  if x < 0 then
    error("negative input: " .. x, 2)  -- 2 = report caller's line
  end
  return math.sqrt(x)
end

-- pcall: protected call (catches errors)
local ok, result = pcall(risky, -5)
if ok then
  print("Result:", result)
else
  print("Error:", result)  -- result is the error message
end

-- With traceback
local ok2, err = pcall(function()
  error("custom error")
end)
if not ok2 then
  print(debug.traceback(err, 2))
end

-- xpcall: with custom error handler
local function handler(err)
  return "Handled: " .. tostring(err) .. "\n" .. debug.traceback()
end

local ok3, result3 = xpcall(function()
  return risky(-1)
end, handler)

-- assert (throws if false/nil)
local function load_config(path)
  local f = assert(io.open(path, "r"), "Cannot open: " .. path)
  return f:read("*a")
end