The math.max
function returns the argument with the maximum value among the provided numbers.
Syntax
math.max(x, ...)
Parameters
- x: A number.
- ...: Zero or more numbers. The function will return the largest value among these parameters.
Return value
The largest of the given numbers. If any parameter is NaN
, it returns NaN
. If no parameters are provided, it returns -inf
.
Description
math.max
compares all the provided arguments using the lua <
operator to determine which one has the maximum value. It is important to note that if any of the arguments are NaN
(not a number), the function will return NaN
.
Examples
Using math.max()
print(math.max(10, 20)) -- 20
print(math.max(-10, -20)) -- -10
print(math.max(-10, 20)) -- 20
print(math.max()) -- -inf
print(math.max(10, 20, 30, 5)) -- 30
print(math.max(5, math.huge)) -- Infinity
print(math.max(1/0, -1/0)) -- Infinity
print(math.max(10, math.nan)) -- NaN
Getting the maximum element of a table
You can use a loop to find the maximum value in a numeric table:
function getMaxOfTable(numTable)
local maxVal = -math.huge
for _, v in ipairs(numTable) do
maxVal = math.max(maxVal, v)
end
return maxVal
end
local numbers = {1, 2, 3, 4, 5}
print(getMaxOfTable(numbers)) -- 5
See also
math.min()
math.mininteger
math.maxinteger