This creates the Clamp(num, lower, upper) mathematical function, which is not part of the standard Lua math libraries.

The argument num is the number or formula to test. lower is the lowest value it can be, and upper is the highest value it can be.

function Clamp(num, lower, upper)
assert(num and lower and upper, 'error: Clamp(num, lower, upper)')
return math.max(lower, math.min(upper, num))

This will constrain the value of myVal between 15 and 25.

for i = 10, 30 do
myVal = Clamp(i, 15, 25)