The assert()
function is a powerful tool in Lua for error handling and debugging. It checks if a given condition is true and raises an error if it's not.
The basic syntax of the assert()
function is:
assert(condition, optional_message)
If the condition is true, assert()
does nothing. If it's false, it raises an error with the optional message.
local x = 10
assert(x > 5, "x should be greater than 5")
print("This line will be executed")
assert(x < 5, "x should be less than 5")
print("This line will not be reached")
In this example, the first assertion passes, but the second one fails, raising an error.
function divide(a, b)
assert(type(a) == "number", "First argument must be a number")
assert(type(b) == "number", "Second argument must be a number")
assert(b ~= 0, "Cannot divide by zero")
return a / b
end
print(divide(10, 2)) -- Output: 5
print(divide(10, 0)) -- Raises an error: Cannot divide by zero
assert()
for checking preconditions in functions.assert()
with Lua Error Handling Basics for robust error management.assert()
in development but removing it in production for performance reasons.While assert()
is invaluable for debugging, it can impact performance in production code. For critical sections, consider using Lua If-Else Statements instead.
To further enhance your error handling skills in Lua, explore these related topics:
By mastering the assert()
function and related error handling techniques, you'll write more robust and reliable Lua code.