Optional Arguments

Everything else that doesn't fall into one of the other PB categories.
Phantomas
User
User
Posts: 96
Joined: Wed Jul 01, 2009 12:59 pm

Optional Arguments

Post by Phantomas »

Example of Procedure with some Optional Arguments:

Code: Select all

Procedure.i proc(one.i, two.i = 1337, three.i = 1337)
  Debug one
  Debug two
  Debug three
EndProcedure
What if I want call this procedure with declare only first (one) and third (three, optional) arguments? I do not want declare second (two, optional) parameter and want keep it default (1337).

In PAWN I can do that:

Code: Select all

proc(0, _, 1338)
"_" means "skip it" and this argument will be equal 1337.

In PureBasic I can not do that:

Code: Select all

proc(0, 1337, 1338)
I should enter second parameter and can not skip it.
User avatar
Tenaja
Addict
Addict
Posts: 1959
Joined: Tue Nov 09, 2010 10:15 pm

Re: Optional Arguments

Post by Tenaja »

No, but if you hardcode the default value in the definition, you can hardcode the value in the call. (Best with a pre-defined #Constant.)
Little John
Addict
Addict
Posts: 4777
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Optional Arguments

Post by Little John »

When using named parameters for a procedure, the order of the parameters doesn't matter, and thus handling of optional parameters is very flexible. It can be implemented e.g. this way (at the expense of speed).
User avatar
Josh
Addict
Addict
Posts: 1183
Joined: Sat Feb 13, 2010 3:45 pm

Re: Optional Arguments

Post by Josh »

Phantomas wrote:"_" means "skip it" and this argument will be equal 1337.
Think is a useful feature and not hard to implement in PB

+1
sorry for my bad english
c4s
Addict
Addict
Posts: 1981
Joined: Thu Nov 01, 2007 5:37 pm
Location: Germany

Re: Optional Arguments

Post by c4s »

+1 for any kind of implementation.

But how about just keeping the desired optional argument empty (instead of using "_") as requested and discussed e.g. here: Procedures - optional parameter more flexible?! That would probably be even easier and more reasonable to implement because "_" is a valid variable name.
If any of you native English speakers have any suggestions for the above text, please let me know (via PM). Thanks!
Trond
Always Here
Always Here
Posts: 7446
Joined: Mon Sep 22, 2003 6:45 pm
Location: Norway

Re: Optional Arguments

Post by Trond »

If the optional parameter can't have the value -1, it can be coded like this:

Code: Select all

#_ = -1

Procedure.i proc(one.i, two.i = 1337, three.i = 1337)
  If two = #_
    two = 1337
  EndIf
  Debug one
  Debug two
  Debug three
EndProcedure

proc(0, #_, 1338)
Fred
Administrator
Administrator
Posts: 18162
Joined: Fri May 17, 2002 4:39 pm
Location: France
Contact:

Re: Optional Arguments

Post by Fred »

Yes, in PB we often use this as well trough the #PB_Ignore or #PB_Default constant.
Post Reply