Skip to content

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

@s-hadinger

Description

@s-hadinger

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions