Page 1 of 1

Optional parameter in method?

PostPosted: Wed May 03, 2006 11:48 am
by vincent
In servoy, can we create "Optional" parameter for method? Pls see below code for more details:

Function fDouble (Optional A)
If IsMissing(A) Then
fDouble = 1
Else
fDouble = A * 2
End If

:?:

PostPosted: Wed May 03, 2006 11:52 am
by patrick
Yes, you can call a method like this:

Code: Select all
fDouble(24)


and then in fDouble you do

Code: Select all
var A = arguments[0];  // receive the (first) argument
if (!A)
{
   ...
}


You can pass as many arguments as you like, since arguments are passed using the arguments array.

Hope this helps.

PostPosted: Wed May 03, 2006 12:06 pm
by vincent
thanks patrick :D ,

I have try the method you've describe but .. what if there's more than 1 arguments,what will happen if i skip 1 arguments?

Normal method:
methodname(arguments[1],arguments[2],arguments[3])

Optional method:
methodname(arguments[1],arguments[3])

In Optional method,i've skip arguments[2]. I've try this in Servoy, and observe the following behaviour:

1.Arguments[3] become Arguments[2]
2.and Arguments[3] = undefined


Any help?

PostPosted: Wed May 03, 2006 1:56 pm
by patrick
If you pass arguments like

Code: Select all
method('a', 'b', 'c')


you fill the arguments array as

Code: Select all
arguments[0] = 'a'
arguments[1] = 'b'
arguments[2] = 'c'


So if you want to skip one argument, you have to do

Code: Select all
method('a', null, 'c')

PostPosted: Wed May 03, 2006 1:56 pm
by bcusick
Hi Vincent,

Yes, you can do this:

Code: Select all
var arg1 = arguments[0]
var arg2 = ''

if(arguments[3] == undefined)
{
  var arg3 = arguments[1]
}
else
{
  var arg3 = arguments[2]
  arg2 = arguments[1]
}


Hope this helps.

PostPosted: Thu May 04, 2006 2:56 am
by vincent
Work like magic. :D This way i can create more generic method.

Thanks Bob and Patrick!

Re: Optional parameter in method?

PostPosted: Wed Jul 07, 2010 2:27 pm
by BulldogBen
Surely best to do it the way Patrick suggested?
Code: Select all
method('a', null, 'c')


That way you are being explicit about which arguments your are skipping.

Re: Optional parameter in method?

PostPosted: Wed Jul 07, 2010 2:59 pm
by ROCLASI
Hi Ben,

You do realize you are responding to a thread that is 4 years old and covers a pretty old version of Servoy ? :)

If you want to use optional values then you can use the following syntax:
Code: Select all
function myFunction(arg1, arg2, arg3) {
    arg3 = arg3||'My Default Value'; // if (false/empty/0/null/undefined) then use the default value

    // rest of your code...
}


Hope this helps.

Re: Optional parameter in method?

PostPosted: Wed Jul 07, 2010 4:44 pm
by BulldogBen
Hint taken, I'll check the posting dates next time.

Damn forum newbies, you've got to love them!