Page 1 of 1

function with multiple default arguments

Posted: Sat Aug 05, 2017 5:56 pm
by HanaIndiana
Not sure why I can't find this question anywhere. I feel like I'm missing something obvious.
Assume there is a function like this:

Code: Select all

function myFunc(a,b,c)
    b = b or 10
    c = c or -1
    print (a,b,c)
end
Since both 'b' and 'c' have defaults, I'm guessing there isn't a way to set 'c', but leave b as default?
Because myFunc(10,20) would set a and b, and leave c as default. Or can you use some type of explicit assignment, like this... myFunc(10,c=20) ?

Re: multiple default arguments

Posted: Sat Aug 05, 2017 5:57 pm
by Nixola
You'd have to do myFunc(10, false, 20) or myFunc(10, nil, 20).

Re: multiple default arguments

Posted: Sat Aug 05, 2017 5:59 pm
by HanaIndiana
I knew I was missing something simple. Much thanks!!
Nixola wrote: Sat Aug 05, 2017 5:57 pm You'd have to do myFunc(10, false, 20) or myFunc(10, nil, 20).

Re: function with multiple default arguments

Posted: Sat Aug 05, 2017 11:31 pm
by davisdude
In this case, nil would be preferred over false because nil represents the absence of a variable, while false could be an argument.

Re: function with multiple default arguments

Posted: Sun Aug 06, 2017 9:29 am
by zorg
davisdude wrote: Sat Aug 05, 2017 11:31 pm In this case, nil would be preferred over false because nil represents the absence of a variable, while false could be an argument.
Yes, but since they're using "or", that doesn't differentiate between them it only cares about whether it's truth-y or false-y.