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.
error() is for real mistakes, such as a function being called with the wrong kind of value. For failures a caller should expect, like a missing item or bad user input, Lua code usually doesn't raise an error. Instead, the function returns nil and a message, and the caller checks the result:
function findItem(inventory, name)
if inventory[name] == nil then
return nil, "No item called " .. name
end
return inventory[name]
end
local count, err = findItem({potion = 3}, "sword")
if count then
print("You have " .. count)
else
print(err) -- No item called sword
endLua's own functions work the same way: tonumber("abc") returns nil, and io.open() returns nil and a message when it can't open a file.
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 BoardPractice on your own: Online Lua compiler