Corona SDK Pro Tip of the Day #31
One of the most used addition to
math library is a
math.clamp() function, which forces a number to be within specific boundaries.
function math.clamp(value, low, high) if low and value <= low then return low elseif high and value >= high then return high end return value end
This function accepts three arguments - number value, low limit and high limit. And it returns a number, which is guranteed to be within these boundaries.
It is good to use it for validation of user input, or to limit player's character movement speed, a color, money and etc. Basically you use it to make sure that a value is within a valid range.
If only one limit (low or high) is provided, then only it is going to be checked.
local actualSpeed = math.clamp(calculatedSpeed, 0, 200) local temperature = math.clamp(temperature, -270) player.x = math.clamp(player.x, 0, map.width) cannon.rotation = math.clamp(cannon.rotation, -90, 90) local age = math.clamp(age, 1, 120) -- Six has higher probability than any other number local luckyDice = math.clamp(math.random(1, 10), nil, 6)