Arrays, Lists, Maps as optional params

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Justin
Addict
Addict
Posts: 832
Joined: Sat Apr 26, 2003 2:49 pm

Arrays, Lists, Maps as optional params

Post by Justin »

It would be nice if you could do this

Code: Select all

Procedure proc(p1, p2, Array a.l(1) = #null)
if a
;do something
endif 
endprocedure
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Re: Arrays, Lists, Maps as optional params

Post by Mistrel »

Objects (as native PureBasic containers are) cannot be null and therefore would be undefined if one were somehow set to null.

While it is possible to get a pointer to the address of an element, there is no way to arbitrarily create a new reference to that container from it. You must always pass a valid instance of the object into scope explicitly.

If you really need a container as an optional parameter right now, a workaround would be to consider storing it in a structure which itself can be null:

Code: Select all

Structure ListIntRef
  List ref.i()
EndStructure

a.ListIntRef

AddElement(a\ref())
a\ref()=1
AddElement(a\ref())
a\ref()=2
AddElement(a\ref())
a\ref()=3

Procedure OptionalList(*SomeList.ListIntRef=#Null)
  If *SomeList
    ForEach *SomeList\ref()
      Debug *SomeList\ref()
    Next
  EndIf
EndProcedure

OptionalList(@a)
OptionalList()
User avatar
Josh
Addict
Addict
Posts: 1183
Joined: Sat Feb 13, 2010 3:45 pm

Re: Arrays, Lists, Maps as optional params

Post by Josh »

+1
sorry for my bad english
Justin
Addict
Addict
Posts: 832
Joined: Sat Apr 26, 2003 2:49 pm

Re: Arrays, Lists, Maps as optional params

Post by Justin »

In the case of arrays i use this workaround to pass them directly, but you lose the array functions so you will need to pass the array size too if you want to iterate:

Code: Select all

EnableExplicit

Structure VECTOR_LONG
	Item.l[0]
EndStructure

Procedure test(*a.VECTOR_LONG = #Null)
	If *a
		Debug *a\Item[0]
		*a\Item[1] = 100
	EndIf 
EndProcedure

Dim a.l(1)

a(0) = 10
a(1) = 20

test(@a())

Debug a(1)
Post Reply