Questioning loop progress

You know how to go thru a set of occurrences using loop and for each statements. When using such constructions, you quickly discover that knowing on which element in the explored collection you are is quite essential. In most situations, either the first (or last) element has something special or you need the index of the current element.

You can use two variations of the this keyword to obtain more information about the progress of the current loop (either in a loop or in a for each statement).

To determine whether the current occurrence is the first in the collection, you can use this’isfirst that evaluates to a boolean which is true when this refers to the first occurrence of the set currently covered.

The variation this’index evaluates to an integer which is the index of the occurrence this currently refers to. That index ranges from 1 to the actual number of occurrences in the covered set. When the this keyword is connected to a loop or a for each statement with multiple or ambiguous paths to document fields, the index is consolidated among all the occurrences addressed by the statement arguments.

No variation similar to this’islast do exists to determine whether this is the last element of a browsed collection. This is because such a determination is tricky and usually weakens DML Blocks execution performances. However, you can test the current index against the number of addressed occurrences to determine whether you’ve reached the end or not, similar to in:

if (this’index = count(…))
{
   …
}

In such situation, never forget to use an intermediate variable to store the count of occurrences. Performing counts takes usually a long time, so take care of doing such a task as less as possible.

To keep execution time acceptable, rather than using an expression similar to the following, which counts only one time rather than counting each time an occurrence is processed:

loop on \\CTA
{
   if (this’index = count(\\CTA))
   …
}

use this one:

%tempo = count(\\CTA);

loop on \\CTA
{
   if (this’index = %tempo)
   …
}

All the variations of this are read-only objects. This means you cannot use this’index in conjunction with the assignment operator (:=) to go directly to one specific occurrence of the covered set. Expressions similar to the following do not move to the fourth occurrence of a set; they are illegal:

this’index := 4

Related Links