Syntax
local ok, result = pcall(function()
return riskyOperation()
end)Examples
Separate failure from an ordinary result
Standalone Luau or a Script in ServerScriptService. The invalid input raises an error; pcall returns false and that error value. The calculation does not continue past error.
local function divide(a: number, b: number): number
if b == 0 then error("Divisor must not be zero") end
return a / b
end
local ok, result = pcall(divide, 8, 0)
if ok then
print(result)
else
print("Calculation failed:", result)
endAttach diagnostic context
Roblox Studio Script in ServerScriptService. The xpcall handler adds a traceback for debugging. Keep the handler non-yielding and do not show internal diagnostics directly to players.
local ok, detail = xpcall(function()
error("Lesson configuration missing")
end, function(message)
return debug.traceback(tostring(message), 2)
end)
if not ok then
warn(detail)
endBest practices
- Check the success flag before using the result; an error string is not loaded player data.
- Keep protected regions narrow so the failure source remains clear.
- Retry only transient operations and use bounded attempts; programming errors need fixes, not endless retries.
Runtime & versions
Luau host; Roblox engine examples require Roblox Studio. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Luau documentation