ForEach

From the Oblivion ConstructionSet Wiki
Jump to navigation Jump to search

A command for Oblivion Script Extender


ForEach is used to iterate over the elements of an array, the characters in a string, or references to objects in a container.

The syntax ForEach item <- collection is used to indicate the variable ("item") which will hold the current element and the string, array, or container reference ("collection") from which elements will be drawn.

On loop entry, item is set to the first element in collection. When the next Loop command is encountered, item is set to the next element in collection and execution returns to the top of the loop. The loop terminates when all elements have been returned. The type of item varies based on the type of collection.


Syntax:

For arrays[edit | edit source]

(nothing) ForEach iterator:array_var <- sourceArray:array

For arrays, item is an array_var, specifically a StringMap. The loop will initialize item with two elements: "key", which holds the key of the current element, and "value", which holds the value associated with that key. Within a ForEach loop you can access both fields via item["key"] and item["value"]. Once the loop terminates, item is reset to an uninitialized array.

For strings[edit | edit source]

(nothing) ForEach iterator:string_var <- sourceString:string

For strings, item is a string_var. The loop initializes item to the first character in the string; on each successive iteration item contains the next character in the string.

For containers[edit | edit source]

(nothing) ForEach iterator:ref_var <- sourceContainer:ref

For containers, item is a ref variable. See the section on Inventory References for details on the usage.

Notes[edit | edit source]

For arrays[edit | edit source]

It's fine to modify the array while iterating over it (removal, insertion, etc).

This includes removing the element associated with the current value of the iterator, considering:

  • If you remove the current entry from a Map or StringMap the iteration will exit.
  • If you remove the current entry from an Array, when you remove the nth entry, iteration will continue with entry n+1.


If you insert an element from within the foreach loop, that element will be included in the iteration if its key is greater than that of the current key when the element is inserted. e.g.:

let someStringMap := ar_map "whatever"::something "stuff"::somethingElse "anotherElement"::moreStuff 

foreach iter <- someStringMap  
  if eval iter->key == "stuff"  
    someStringMap->things := chickens  
    someStringMap->blah := etc  
  endif  
loop

After the insertion the next element in the iterator will be "things". The iterator will never get to "blah".


See Also[edit | edit source]