for

The for keyword introduces an execution loop.

Purpose

A statement for executing a statement block as many times as matching objects are found to start the action.

Context

Functions or rule actions

Syntax

for (initialize; test; increment) statement;  

Description

Use the for statement in the action part of rules and in functions to execute multiple times the statement or a block of statements enclosed in braces ({}). The initialize, test, and increment arguments can be any valid expression, as in the Java™ programming language. The statement block can execute any IRL statement and any arithmetic expressions and method calls.

Example

The ConnectivityUpdate rule tests whether a new node exists in the network and adds a link to it from each of its neighbors.

rule ConnectivityUpdate{
   when {
      ?n: Node(state == NEW; ?neighbors: neighbors() );
   }
   then {
      for (int ?i = 0; ?i < ?neighbors().size(); ?i++) {
         ( (Node)?neighbors().elementAt(i) ).addLink(?n); 
      }
      update (?n);
   }
};

This rule is processed as follows:

  1. The rule condition matches an object Node when the field state equals the static value NEW and it binds the variable ?neighbors with the vector field neighbors().

  2. If such a Node object is found, the action part can be executed. The variable ?i is initialized to 0. The for statement loops for each neighbor and the addLink(?n)method updates the links from the neighbors to the new node.

  3. The last action uses the update command to update the agenda with the new node.