Iterating over an array - three different for-loops

From Remeis-Wiki
Jump to navigation Jump to search

for

The traditional C-like for-loop is defined as follows:

for (initialization; condition; increment/decrement) {
  statement;
}

This is very general, just because nearly everything is possible! The three required expressions may contain any code and may not contain numbers: \\

words = ["hello", "hi", "welcome", "me", "you", "they", "meet", "talk", "email"];
for (sentence = ""; urand() < .9; sentence += words[int(urand*length(words))] + " ") {
  print(sentence);
}

As you can see, the traditional for-loop is extremely flexible. But for the sake of speed! That is because the three expression are evaluated during each iteration!

_for

As soon as you like to loop over integer numbers (for instance over the indices of an array) you don't need the above flexibility. Thus, you should use another for-loop, which is defined for this purpose only (see also the S-Lang manual):

_for variable (start, end, increment/decrement) {
  statement;
}

For instance:

_for i (0, length(myarray)-1, 1) {
  print(myarray[i]);
}

Since S-Lang pre2.3.0-75, it is possible to omit 1 as the third argument of the _for statement, reducing the above example to

_for i (0, length(myarray)-1) {
  print(myarray[i]);
}

foreach

The last possibility to iterate through an array is to use the foreach-loop (in case you don't need the position of the element within the array). The following example is equivalent to the above one:

foreach value (myarray) {
  print(value);
}