FOR EACH Statement

Help Contents

Introduction

The FOR EACH statement executes a list of statements for each item in a collection. The FOR EACH statement has this syntax:

FOR EACH variable IN collection-value DO
    statement;
    statement;
    ..
    statement;
END_FOR;

Where:

Execution Logic

The FOR EACH Loop uses this logic to execute statements:

  1. The method GetEnum is called on the collection-value parameter to obtain an iterator object.
  2. The method GetFirst is called on the iterator object.
  3. If the returned object is not defined, steps 4, 5 and 6 are skipped. Execution continues with the next statement after the END_FOR keyword.
  4. Each statement inside the loop is executed in order.
  5. The method GetNext is called on the iterator object.
  6. Execution continues with Step 3.

To stop the FOR EACH loop early (before the loop variable reaches its target value) use the EXIT Statement.

Examples

  1. Execute code in a loop 6 times:
    VAR
        A, List : VARIANT;
        StringValue : STRING;
    END_VAR
    
        List := SysCreateInstance( "fhs.LinkedList" );
        List.AddLast( 'One' );
        List.AddLast( 'Two' );
        StringValue := '';
    
        FOR EACH A IN LIST DO
            StringValue := StringValue || TO_STRING( A );
        END_FOR;
    END_PROGRAM

    Note: When completed the StringValue variable will be STRING#'OneTwo'.

Standards Compliance

FOR EACH is not part of the IEC 61131-3 standard.

Further Information

Structured Text

For other Structured Text (ST) statement types.

Variable Reference

To learn about variable references that can be used for the variable.

Expressions

To learn about expressions that can be used for start-value, end-value, and step-value.

Glossary

For the meaning of terms used in Fernhill SCADA.