Atom

math.clamp()

Restricts x to an inclusive interval.

Signature

math.clamp(x, low, high)

Parameters

Three ordered numbers with low <= high.

Returns

One of the three original values.

Behavior

Returns x when already within bounds.

Errors

Unordered input or reversed bounds.

Example

Atom
use math
assert(math.clamp(9, 0, 4) == 4)

Keep a level within its allowed range

Give the value, the minimum, and the maximum.

Atom
use math
print(math.clamp(12, 0, 10))
print(math.clamp(7, 0, 10))
Output
10
7

The first value is above the maximum. The second value is already within the range.