GLBasic User Manual

Main sections

FOREACH

FOREACH ref IN field[]
...
NEXT



With the FOREACH statement you can quickly iterate through an array and perform an operation on every item.
During the loop, "ref" will be a pointer (BYREF) variable to each element in the array.
You do not need to define "ref" as LOCAL as it will be done automatically. "ref" will invalid after the corresponding 'NEXT' command.

The following code is the equivalent of the FOREACH statement:
FOR i = 0 to BOUNDS(field[],0)-1
ref = field[i]
...
field[i] = ref
NEXT


Example / Beispiel:
// --------------------------------- //
// Project: ForEach

// Make an array of numbers
// Ein Feld von Zahlen
DIMDATA a[], 12,14,15,17

// Enumerate the numbers
// Die Zahlen durchlaufen
FOREACH num IN a[]
    a$=a$ + num + ", "
NEXT
PRINT a$, 0,0

// a simple TYPE
// ein einfacher TYPE
TYPE SHOP
    milk$
ENDTYPE

// An array-instance of it
// Eine Feld-Instanz davon
LOCAL kmart[] AS SHOP

// Fill with values
// Mit Werten f├╝llen
DIM kmart[3]
    kmart[0].milk$ = "fat free"
    kmart[1].milk$ = "fatty"
    kmart[2].milk$ = "butter"

    a$=""
    // Enumerate all milk values
    // Alle shops durchlaufen
    FOREACH item IN kmart[]
        a$ = a$ + item.milk$ + ", "
    NEXT
    PRINT a$, 0, 40


    SHOWSCREEN
    MOUSEWAIT


Output:
12, 14, 15, 17,
fat free, fatty, butter,

See also...