Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: add arguments to int() to guard value and add default #431

Open
s-hadinger opened this issue Jun 15, 2024 · 4 comments
Open

Proposal: add arguments to int() to guard value and add default #431

s-hadinger opened this issue Jun 15, 2024 · 4 comments

Comments

@s-hadinger
Copy link
Contributor

s-hadinger commented Jun 15, 2024

int() currently takes only one argument, and return nil if the argument is nil

I'm facing a lot of code where I need to guard the value within a range and potentially define a default value.

if (i == nil)  i = 0 end
if (i < 0) i = 0 end
if (i > 100) i = 100 end

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:

i = int(i, 0, 100, 0)

It could also used without a default value, hence forcing an int between 0 and 100 or nil

int(-1, 0, 100)     # 0
int(1, 0, 100)      # 1
int(101, 0, 100)    # 100
int(2.5, 0, 100)    # 2
int(nil, 0, 100)    # nil

@skiars any opinion on this proposal?

Note: code impact would be minimal, and no impact on performace

@s-hadinger
Copy link
Contributor Author

@skiars any opinion for or against it? If not I will implement it as described above.

@skiars
Copy link
Member

skiars commented Jun 28, 2024

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

@s-hadinger
Copy link
Contributor Author

s-hadinger commented Jun 28, 2024

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)

@skiars
Copy link
Member

skiars commented Jun 29, 2024

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)
  • In Python, the default constructor of int() is 0, but it may raise an error during parsing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants