Error Handling with pcall/xpcall
Lua uses pcall
(protected call) and xpcall
for error handling instead of try/catch blocks.
Using pcall:
local status, err = pcall(function()
error("Something went wrong!")
end)
if not status then
print("Error: " .. err)
end
pcall
returns a boolean status and an error message if the function fails.
Using xpcall:
local function errorHandler(err)
print("Caught an error: " .. err)
end
xpcall(function()
error("Another error!")
end, errorHandler)