lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Sean Conner <sean@conman.org> wrote:
> > -----
> > -- What I use to do to have 'named arguments' in Lua
> > function func(opt)
> >   opt = opt or {}
> >   local arg1 = opt.arg1 or "default1"
> >   local arg2 = opt.arg2 or "default2"
> >   -- use arg1 & arg2
> > end
> >
> > func({arg1 = 1, arg2 = 2})
>
>   You can drop the parenthesis in this case:
>
>         func { arg1 = 1 , arg2 = 2 }

Yeah sure, but to me the bad thing about this is 1/ the intermediate table for
the args, and 2/ the need to manually de-construct the table at the beginning
of the function.

>   I would have constructed it like:
>
> def foo(x,y,z,a = 1 , b = 2 , c = 3)
> end
>
>   Calling foo() would be
>
> foo(1,2,3,4,5,6)
> foo(x = 1 , y = 2 , z = 3 , a = 4 , b = 5 , c = 6)
> foo(*{1,2,3,4,5,6}) # the "splat" operator I guess
> foo(**{"x",5,"y",6,"z",7}) # assuming I got the "splatsplat" operator right
>
>   Instead of complicating the definition, make it so you can do whatever you
> want.  I mean, you could mix things up:
>
> foo(1,2,3,a = 4 , b = 5 , c = 6)
> foo(*{1,2,3},4,5,6)
> foo(1,2,**{"z",5,"b",7})

I'm not sure what you mean, but what you're suggesting is possible in
Crystal, for
example the code:

#-----------------------
def foo(x, y, z, a = 1, b = 2, c = 3)
  puts "#{x}, #{y}, #{z}, #{a}, #{b}, #{c}"
end

foo 1, 2, 3, 4, 5, 6
foo x: 1, y: 2, z: 3, a: 4, b: 5, c: 6
foo *{1, 2, 3, 4, 5, 6}
foo **{x: 5, y: 6, z: 7}

puts "You could mix things up"

foo 1, 2, 3, a: 4, b: 5, c: 6

one_two_three = {1, 2, 3}
foo *one_two_three, 4, 5, 6

foo 1, 2, **{z: 5, b: 7}
#-----------------------

Gives:

#-----------------------
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
5, 6, 7, 1, 2, 3
You could mix things up
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
1, 2, 5, 1, 7, 3
#-----------------------

(live at https://carc.in/#/r/3jwq)