clamp

function clamp( num, min, max ) --> res

Description

If num is less than min returns the function min. If num is greater than max returns the function max. In all other cases returns the function num.

Parameters

num

The value that should fit into a range.

min

The minimum value that should be returned.

max

The maximum value that should be returned.

Return Values

res

The function returns num, min or max.

Code

--ZFUNC-clamp-v1
local function clamp( num, min, max ) --> res
   if num < min then return min
   elseif num > max then return max
   else return num
   end
end

return clamp

Examples

local t = require( "taptest" )
local clamp = require( "clamp" )

min = 2
max = 11

t( clamp( 2, min, max ), 2 )
t( clamp( 7, min, max ), 7 )
t( clamp( 11, min, max ), 11 )

t( clamp( 1, min, max ), 2 )
t( clamp( 12, min, max ), 11 )

t()

Inspired by

Inspired by