Thought I’d share this one liner…
I have a situation where I need a value to be in a specific range, regardless of what value is provided… The Upper value limit may be set to -1 (indicated no limit)
If maxLimit is -1 then the value is clamped to the range of Zero to “anything”
if maxLimit is anything else if new_value will be forced to be Zero to MaxLimit
of course the Max(0 portion could also be expanded to allow fully custom ranges, but for my app it needed only positive values
This is much shorter than
new_value=old_value
if new_value<0 then
new_value=0
elseif new_value>maxLimit and maxLimit>0 then
new_value=maxLimit
just a tip to perhaps spark an idea on changing something you may have thought to be too verbose
If speed is your concern (like millions of clamps) the last time I tested this the longer code version (if v < minval then v = minval…) is significantly faster than using Min() Max().
This is clearly a case where it’s more readable as a proper function, but much faster as code - it would be nice if there was an #inline pragma like C has. Turns out there’s a feature request from 2002 on this: <https://xojo.com/issue/3712>