How to define a function with optional arguments?

I couldn’t find anything in the manual about optional arguments. The best workaround I could think is to make the function take a single argument and pass an array to it. Then it’s just a matter of dealing with different sizes of arrays inside the function:

fn print_args argument
        if eq 1 $len(@argument)
                echo @argument[0]
        else if eq 2 $len(@argument)
                echo @argument[0]
                echo @argument[1]
        end
end

or

fn print_args argument
        echo @argument[0] $or(@argument[1] "baz")
end

I suppose this works for most cases. In a script I could pass @args to it and deal with flags that way. I think being able to specify default values for arguments could make things cleaner though.

I also found one situation where this is annoying: When setting up a convenience function in ~/.config/ion/initrc, it forces me to wrap the arguments in brackets or quotes every time I use it on the command line.

1 Like