The math.abs()
function in lua returns the absolute value of a number, which is the maximum value between the number x
and its negation -x
.
Syntax
math.abs(x)
Parameters
x
A number (integer or float).
Return value
The absolute value of x
. If x
is negative, it returns -x
(a non-negative value). If x
is already non-negative, it returns x
itself.
The result is always a non-negative number.
Description
math.abs()
is a static function in lua, and you always call it using math.abs()
rather than as a method of an object.
Examples
Using math.abs()
print(math.abs(-10)) -- 10
print(math.abs(0)) -- 0
print(math.abs(5)) -- 5
print(math.abs(-3.14)) -- 3.14
Coercion behavior
math.abs()
expects a numeric argument. Passing non-numeric values will result in a runtime error.
-- Correct usage:
print(math.abs(42)) -- 42
-- Incorrect usage:
-- print(math.abs("string")) -- Error: bad argument #1 to 'abs' (number expected, got string)
See also
math.floor()
math.ceil()
math.sqrt()
math.max()