Open s-hadinger opened 3 months ago
@skiars any opinion for or against it? If not I will implement it as described above.
I'm a bit confused about the use of min
and max
, but not default
. I suggest naming this argument default
instead of def
, because def
is a keyword.
Gating of numeric ranges is typically done using specialized functions, which helps in maintaining semantic clarity. I would suggest adding these to the math library:
def min(a, b)
return a < b ? a : b
end
def max(a, b)
return a > b ? a : b
end
def bound(lower, value, upper)
return max(lower, min(value, upper))
end
Thanks, using a default value was indeed a bad idea and makes the syntax confusing.
I agree that min/max are missing.
But then the syntax would be:
v = math.bound(0, int(v), 10)
The v = math.bound(0, int(v), 10)
is pretty readable. As for the default value of int()
, let's take a look at other languages:
parseInt()
in JavaScript returns NaN
by default (I don't like NaN
, it can easily break calculations)int()
is 0
, but it may raise an error during parsing
int()
currently takes only one argument, and returnnil
if the argument isnil
I'm facing a lot of code where I need to guard the value within a range and potentially define a default value.
I'm proposing to have new optional arguments:
int(arg:any, [min: int, max: int, def: int or nil]) -> int or nil
With this the above code would look like:
It could also used without a default value, hence forcing an
int
between0
and100
ornil
@skiars any opinion on this proposal?
Note: code impact would be minimal, and no impact on performace