foreach1.3

foreach list command (foreach list1 ... command)

With a single list, runs the command for each item of list. command may be the name of a command, or an anonymous command created with ->.

foreach [1.1 2.2 2.6] show
=> 1.1
=> 2.2
=> 2.6
foreach [1.1 2.2 2.6] [ x -> show (word x " -> " round x) ]
=> 1.1 -> 1
=> 2.2 -> 2
=> 2.6 -> 3

With multiple lists, runs command for each group of items from each list. So, they are run once for the first items, once for the second items, and so on. All the lists must be the same length.

Some examples make this clearer:

(foreach [1 2 3] [2 4 6]
   [ [a b] -> show word "the sum is: " (a + b) ])
=> "the sum is: 3"
=> "the sum is: 6"
=> "the sum is: 9"
(foreach list (turtle 1) (turtle 2) [3 4]
  [ [the-turtle num-steps] -> ask the-turtle [ fd num-steps ] ])
;; turtle 1 moves forward 3 patches
;; turtle 2 moves forward 4 patches

See also map, -> (anonymous procedure).

Take me to the full NetLogo Dictionary