Up: The for Statement [Contents][Index]

#### 10.5.1 Looping Over Structure Elements

A special form of the `for` statement allows you to loop over all the elements of a structure:

    for [ val, key ] = expression
      body
    endfor

In this form of the `for` statement, the value of expression must be a structure. If it is, key and val are set to the name of the element and the corresponding value in turn, until there are no more elements. For example:

    x.a = 1
    x.b = [1, 2; 3, 4]
    x.c = "string"
    for [val, key] = x
      key
      val
    endfor

         -| key = a
         -| val = 1
         -| key = b
         -| val =
         -|
         -|   1  2
         -|   3  4
         -|
         -| key = c
         -| val = string

The elements are not accessed in any particular order. If you need to cycle through the list in a particular way, you will have to use the function `fieldnames` and sort the list yourself.