Quirrel4.41.0

math.clamp

Defined in module "math"
from "math" import clamp
pure fastcall clamp(x: number, min: number, max: number): number

Clamps x to the range [min, max]

Parameters

xnumbervalue to clamp
minnumberlower bound of the range
maxnumberupper bound of the range

Return value

min if x is below the range, max if it is above, otherwise x itself.

Errors

Throws Invalid clamp range: min>max when min > max. The range is checked before x is read, so an inverted range always throws, whatever x is.

Notes

The bound that wins is returned unchanged, so the result keeps the type of that argument and not of x: clamp(15, 0, 10.0) gives the float 10.0, while clamp(5, 0.0, 10.0) gives the integer 5. Keep the bounds and the value in one type when the caller expects a fixed result type.

Comparison is raw, so a _cmp metamethod on an instance is not consulted.

Example

examples/math/clamp.nut
from "math" import clamp

println("clamp(3, 0, 10) =", clamp(3, 0, 10))
println("clamp(15, 0, 10) =", clamp(15, 0, 10))
println("clamp(-1.5, 0.5, 1.0) =", clamp(-1.5, 0.5, 1.0))

// the winning bound is returned as is, so its type wins
println("type(clamp(15, 0, 10.0)) =", type(clamp(15, 0, 10.0)))
println("type(clamp(5, 0.0, 10.0)) =", type(clamp(5, 0.0, 10.0)))

try {
  clamp(1, 10, 0)
} catch (e) {
  println("clamp(1, 10, 0) throws:", e)
}
Output:
clamp(3, 0, 10) = 3
clamp(15, 0, 10) = 10
clamp(-1.5, 0.5, 1.0) = 0.5
type(clamp(15, 0, 10.0)) = float
type(clamp(5, 0.0, 10.0)) = integer
clamp(1, 10, 0) throws: Invalid clamp range: min>max

See also

minReturns the minimum value from the arguments
maxReturns the maximum value from the arguments
absReturns the absolute value of x
mathmodule index