Page 1 of 1

allow empty arrays

Posted: Sun Dec 04, 2016 4:34 pm
by #NULL
why not allow to specify -1 or nothing for Dim and ReDim to define an empty array?
a modified example of ExtractXMLArray() shows me that pb can handle empty arrays already:

Code: Select all

Xml$ = "<array></array>"
;Xml$ = "<array><element>1</element><element>10</element><element>100</element></array>"

If ParseXML(0, Xml$) And XMLStatus(0) = #PB_XML_Success
  Dim MyArray(0) ; will be resized by the next call
  ExtractXMLArray(MainXMLNode(0), MyArray())
  
  Debug "ArraySize : " + ArraySize(MyArray())
  For i = 0 To ArraySize(MyArray())
    Debug MyArray(i)
  Next i
Else
  Debug XMLError(0)
EndIf
currently for an 'add' routine i did something like the following, including the fixing of the array size when you are done with adding values.

Code: Select all

Procedure addColor(Array colors(1), color)
  colors(ArraySize(colors())) = color
  ReDim colors(ArraySize(colors()) + 1)
EndProcedure

Dim colors1(0)

addColor(colors1(), $ffff3333)
addColor(colors1(), $ffff5555)
addColor(colors1(), $ffff6666)
ReDim colors1(ArraySize(colors1()) - 1)
now at least i know i can create empty arrays via xml parsing.

Re: allow empty arrays

Posted: Sun Dec 04, 2016 5:28 pm
by #NULL
here is an xml version of clearArray() for one dimensional integer arrays

Code: Select all

Procedure clearArray(Array arr(1))
  Protected xml
  xml = ParseXML(#PB_Any, "<array></array>")
  If xml
    If XMLStatus(xml) = #PB_XML_Success
      ExtractXMLArray(MainXMLNode(xml), arr())
    Else
      Debug "XMLError: " + XMLError(xml)
    EndIf
    FreeXML(xml)
  Else
    Debug "ParseXML() failed."
  EndIf
EndProcedure

Procedure addValue(Array arr(1), value)
  ReDim arr(ArraySize(arr()) + 1)
  arr(ArraySize(arr())) = value
EndProcedure

Dim values(0)
clearArray(values())
addValue(values(), 123)
addValue(values(), 456)

Debug "ArraySize : " + ArraySize(values())
For i=0 To ArraySize(values())
  Debug values(i)
Next

Re: allow empty arrays

Posted: Sun Dec 04, 2016 11:08 pm
by IdeasVacuum
what difference does it make though?

Re: allow empty arrays

Posted: Mon Dec 05, 2016 8:00 am
by nco2k
to not waste resources and cpu time. :D

seriously though, sometimes you have to call a function first, to find out the required number of elements. once you know that number, you can redim your array and fill it with data. dim allocates and zeroes the memory and redim preserves the existing data. its kind of a total waste in this case.

pseudocode:

Code: Select all

Protected Dim MyArray.MyStructure(-1), Count

ApiStuff_(0, @Count)

ReDim MyArray(Count - 1)

ApiStuff_(@MyArray(), @Count)

For i = 0 To Count - 1
  Debug MyArray(i)\Whatever
Next
c ya,
nco2k

Re: allow empty arrays

Posted: Mon Dec 05, 2016 8:14 am
by Mistrel
It still bothers me that arrays allocate with n+1 the initial size. I always forget this since it's always n in every other language I use.