The error() Function
Part of the Logic & Flow section of Coddy's Lua journey — lesson 32 of 54.
Sometimes your code needs to stop immediately when something goes wrong. Lua provides the error() function to handle these situations by raising an error and halting script execution.
The error() function takes a message as its argument and stops the program, displaying that message to indicate what went wrong. Here's the basic syntax:
error("Something went wrong!")This is particularly useful when validating function inputs. For example, if a function expects a positive number but receives a negative one, you can use error() to prevent further execution:
function calculateSquareRoot(num)
if num < 0 then
error("Cannot calculate square root of a negative number")
end
return math.sqrt(num)
endWhen error() is called, the program stops immediately at that point and displays your custom error message. This helps you catch problems early and communicate clearly what went wrong, making your code more reliable and easier to debug.
Cheat sheet
The error() function stops program execution and displays an error message:
error("Something went wrong!")Common use case - validating function inputs:
function calculateSquareRoot(num)
if num < 0 then
error("Cannot calculate square root of a negative number")
end
return math.sqrt(num)
endWhen error() is called, the program halts immediately and displays the custom error message.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board