QB64.org Forum
Active Forums => QB64 Discussion => Topic started by: stoneskipper on October 02, 2018, 09:53:15 pm
-
Looking for opinions/feedback on the usefulness of the following code implementation -- a shorthand for longer blocks of implicit code, commonly encountered:
__________
LCAP & UCAP
Cap/limit a variable's min/max value. Possibly referencing the current/floating val of another variable, or else fixed with option parameter, eg., "F". Capped variable values are assessed/adjusted only during assignment. Hypothetical examples:
LCAP X (-4.5) ' IF X < -4.5 then X = -4.5
X = 2 - 10
print X
>> -4.5
- - - - - - - - - -
UCAP X (A + 5): LCAP Y (X) ' IF X > A + 5 then X = [Current Value of A] + 5
A = 4: X = 10: Y = 4 ' & IF Y < X then Y = [Current Value of X]
print X; Y
>> 9 9
A = 3
print X; Y
>> 9 9
X = X: Y = -Y ' X / Y retain value until reassigned/reassessed
print X; Y
>> 8 8
- - - - - - - - - -
UCAP X (A + 5), F: LCAP Y (X) ' X-Max locks at 1st assigned value vs. A (unless eg., _FREECAP), Y can float
A = 4: X = 10: Y = 4
print X; Y
>> 9 9
A = 3
print X; Y
>> 9 9
X = X: Y = -Y
print X; Y
>> 9 9
- - - - - - - - - -
UCAP X (A + 5): LCAP Y (X), F ' Y-Min locks at 1st assigned val vs. X, X can float
A = 4: X = 10: Y = 4
print X; Y
>> 9 9
A = 3
print X; Y
>> 9 9
X = X: Y = -Y
print X; Y
>> 8 9
-
I don't know how I feel about it.
-
... Any arguments, personal or abstract, either for or against, beyond the ambiguous feeling?
-
This reminds me of two functions max and min that are used say to keep x and y inbounds of screen.
rightSide = 800
x = x + 10
x = min( x, rightSide) 'want x to be always to left of right border
>> x never goes beyond right border
Actually can write those two lines as:
x = min(x+10, rightSide)
Sorry I keep adding stuff:
Modulus is used like this.
-
I use a similar function, but it wraps to a value between min and Max (inclusive) as part of a HashTable calculation and does not use MOD.
Function keepinrange#(x as double, min as double, max as double)
If max > min then
y# = x
Do
If y# < min then
y# = y# - min + max
Elseif y# > max then
y# = y# - max + min
Else
keepinrange# = y#
Exit function
End if
Loop
Else
keepinrange# = min
End if
-
We've all had to cap a value either to a lower or upper boundary. A custom function for that is a breeze to write.
What I don't feel strongly about is having a value being constantly monitored and capped in the background by an external force (one that isn't explicitly coded by the user).
-
I agree with Felipe. Don't add overhead monitoring and capping values to a range. One simple per-need call is all that's necessary and adds zero cpu overhead except when explicitly called.