Error Handling: pcall, xpcall, and error
Lua doesn't have try/catch, instead errors are handled with the built-in functions pcall, xpcall, error, and assert.
Raising errors
Calling error(message) immediately stops execution and unwinds the call stack, exactly like throw in other languages, except the "catch" is a separate function call rather than a block.
Catching errors with pcall
pcall ("protected call") runs a function and catches any error it raises. It always returns a boolean first (true if no error, false if one occurred), followed by either the function's return value(s), or the error message.
assert: a shortcut for a common check
assert(condition, message) is sugar for "if condition is falsy, error(message)", used constantly to validate function arguments up front.
xpcall: catching errors with a custom handler
xpcall is like pcall but takes a second argument, a message handler that runs while the stack is still unwound (useful for attaching a stack trace, or normalizing non-string error values like the table above).
TIP
Reach for assert for "this should never happen if the caller used the API correctly" checks, and reserve error + pcall for situations the caller is expected to actually handle, like a failed network request or invalid user input.