Lua for Beginners: Error Handling — Handling Things That Go Wrong with pcall & assert | Episode 27
Video: Lua for Beginners: Error Handling — Handling Things That Go Wrong with pcall & assert | Episode 27 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua for Beginners: Error Handling — Handling Things That Go Wrong with pcall & assert
Lua provides powerful tools to handle errors gracefully, allowing your programs to detect and respond to problems without crashing unexpectedly. In this guide, you'll learn how to raise errors with error(), catch them safely using pcall() and xpcall(), validate conditions with assert(), and use the idiomatic ok, err pattern for robust error handling.
Code
-- Raise an error explicitly
local function fail()
error("Something went wrong!") -- stops execution and raises an error
end
-- Use pcall to catch errors safely
local ok, err = pcall(fail)
if not ok then
print("Caught error with pcall:", err)
end
-- Safe division using assert to validate input
local function safe_divide(a, b)
assert(type(a) == "number" and type(b) == "number", "Both arguments must be numbers")
assert(b ~= 0, "Division by zero!")
return a / b
end
local ok, result_or_err = pcall(safe_divide, 10, 0)
if ok then
print("Result:", result_or_err)
else
print("Error:", result_or_err)
end
-- xpcall with a custom error handler to get stack trace
local function error_handler(err)
return "Custom error handler: " .. tostring(err) .. "\n" .. debug.traceback()
end
local function cause_error()
error("An unexpected error occurred")
end
local ok, err = xpcall(cause_error, error_handler)
if not ok then
print(err)
end
-- Idiomatic ok, err pattern example
local function might_fail(flag)
if flag then
return true, "Success!"
else
return false, "Failure reason"
end
end
local ok, msg = might_fail(false)
if ok then
print("Operation succeeded:", msg)
else
print("Operation failed:", msg)
end
Key Points
error()raises an error and stops the current execution flow immediately.pcall()runs a function safely, returningtrueand the result on success, orfalseand the error message on failure.xpcall()extendspcall()by allowing a custom error handler to produce detailed error reports like stack traces.assert()validates conditions and raises an error with a message if the condition is false or nil.- The idiomatic Lua error handling pattern returns
ok, errpairs, whereokis a boolean indicating success or failure.