The math.min function returns the argument with the minimum value among the provided numbers.

Syntax

math.min(x, ...)

Parameters

  • x: A number.
  • ...: Zero or more numbers. The function will return the smallest value among these parameters.

Return value

The smallest of the given numbers. If any parameter is NaN, it returns NaN. If no parameters are provided, it returns math.huge.

Description

math.min compares all the provided arguments using the lua < operator to determine which one has the minimum 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.min()

print(math.min(10, 20))            -- 10
print(math.min(-10, -20))          -- -20
print(math.min(-10, 20))            -- -10
print(math.min())                   -- Infinity
print(math.min(10, 20, 30, 5))     -- 5
print(math.min(-math.huge, 0))     -- -Infinity
print(math.min(5, math.nan))       -- NaN

Getting the minimum element of a table

You can use a loop to find the minimum value in a numeric table:

function getMinOfTable(numTable)
    local minVal = math.huge
    for _, v in ipairs(numTable) do
        minVal = math.min(minVal, v)
    end
    return minVal
end

local numbers = {1, 2, 3, -4, 5}
print(getMinOfTable(numbers))      -- -4

See also

  • math.max()
  • math.mininteger
  • math.maxinteger

Was this page helpful?

Table of Contents