Please enable JavaScript to view this site.

DAQFactory User's Guide

Navigation: 5 Sequences & Scripting

5.15 Looping while counting with the for statement

Scroll Prev Top Next More

If instead of looping until a condition occurs you want to loop a certain number of times then the for statement is a better choice.  For example:

 

for (Private Counter = 0, Counter < 10, Counter++)

  do something...

endfor

This is the same as:

 

Private Counter = 0

while (Counter < 10)

  do something...

  Counter++

endwhile

The for statement is made up of three parts.  The first part, Private Counter = 0 is executed the first time the for statement is reached.  In this case, we initialize the Counter variable to 0.  By using the Private in front of the counter variable, we declare (if necessary) and assign the initial value in one step.  This saves us from having to do:

 

Private Counter

for (Counter = 0, Counter < 10, Counter++)

  do something...

endfor

The code between the for and the endfor statements will then execute repeatedly until the second term Counter < 10 no longer evaluates to true.  The final term of the for statement gets executed every time the for loops.  The first and last term are both statements and can perform anything you can normally do with a single sequence step.  The middle term is an expression and should evaluate to a number.

For statements can also utilize the break statement to prematurely break out of a for loop, and the continue statement, to prematurely loop back to the for statement:

 

for (Private Counter = 0, Counter < 10, Counter++)

  if (Input[0] > 5)

    break

  endif

  if (Input[0] < 3)

    delay(1)

    continue

  endif

  Output = Counter

  delay(1)

endfor

The above example loops up to ten times.  If Input ever goes above 5, the loop stops and jumps to any steps after the endfor.  If Input is less than 3 than the loop does nothing, but if it is between 3 and 5, Output is set to the current value of Counter.  Notice how we include delay() statements in the for loop.  Delay or wait statements are needed to prevent the loop from running to quickly and stalling DAQFactory.