Page 1 of 1

Low() and High() functions like in Pascal/Delphi

Posted: Fri Jun 07, 2019 3:57 pm
by kpeters58
Wish there were Low() and High() functions like in Pascal/Delphi (applicable to all data types that have defined low & high values).

Among other use cases, especially handy for looping over arrays in that it frees the programmer from having to use literal index numbers (similar to foreach).

One could do:

Code: Select all

Dim MyArray(666)
For index = Low(MyArray) to High(MyArray)
   MyArray(index) ...
Next
No more need to go through code to adjust loops etc. whenever the dim's of an array change

Re: Low() and High() functions like in Pascal/Delphi

Posted: Fri Jun 07, 2019 4:04 pm
by skywalk
That will be slow for large arrays. You have 2 redundant calculations at top of For loop.

Re: Low() and High() functions like in Pascal/Delphi

Posted: Fri Jun 07, 2019 4:15 pm
by Marc56us
For Arrays, in PB low() are always 0 and for high() we have ArraySize()

:idea: it is also preferable to assign the function to a value to avoid recalculation at each iteration.

Code: Select all

Array_Size = ArraySize(MyArray())
For index = 0 To Array_Size
   MyArray(index) ...
Next

Re: Low() and High() functions like in Pascal/Delphi

Posted: Fri Jun 07, 2019 4:26 pm
by #NULL
Marc56us wrote:For Arrays, in PB low() are always 0
There are some exceptions. JSON/XML extracted arrays can be empty. Global arrays declared in a procedure that is not called are also empty.

Re: Low() and High() functions like in Pascal/Delphi

Posted: Fri Jun 07, 2019 7:28 pm
by kenmo
#NULL wrote:
Marc56us wrote:For Arrays, in PB low() are always 0
There are some exceptions. JSON/XML extracted arrays can be empty. Global arrays declared in a procedure that is not called are also empty.
It still works: ArraySize() returns -1 for an empty extracted array, and a For loop from 0 to -1 simply doesn't execute.


I don't fully understand the original post. If you use ArraySize() or constants/variables for array sizes, you don't need to "adjust loops whenever the dims change".


A feature I would like to see is ForEach to work with Arrays, automatically handling the indexing. (Like a List or Map.)

Code: Select all

Dim Test.i(10)

ForEach Test()          ; Notice, no array index.
  Test() = Random(100)  ; Of course this syntax would only work within a ForEach loop
Next