While loop
  > Home
v User Guide
    > Introduction
    > Hello World
    v Flow Control
       o If-else
       o Switch
       o Foreach loop
       o While loop
       o For loop
    > Function Calls
    > Authentication
    > Database access
    > Content Management
    > Remote Calling
    > Object-Oriented
    > Other Features
> Reference
> Portal Object
> Development Guide

sys Class
debug Class
Intrinsic Conversions
>> User Guide >> Flow Control >> While loop <=  =>      <  1  >  
While loop

There are not many loops that we cannot code with "foreach" and must use "while" instead.  However, using a "while" with a condition looks more natural to most programmers than using a foreach loop starting with an if-break statement.

For example, we can do database operation as in the foreach example:

database prod query="select * from Product";

var prodrec = "(db)prod";

while ({#prodrec} > 0 && '{status%database}' == 0) {

   if ('{prodrec:Price}' != 0) {

         display "Product {result%while:iteration}: ";
         display "{prodrec:Name} ({prodrec:Code}) costs ";

         display "{prodrec:Price} per {prodrec:Unit}<br>\n";


   var prodrec = "(db)prod";



Please note that retrieving beyond the last record in the record set does not generate an error.  That is why we need to check the size of the retrieved record to determine if the end of record set is reached.  Also, because the "while" loop check-first-before-run, you need to fetch-ahead the first record before the loop starts, and fetch subsequent record at the end of the loop before the next iteration.

Same as in "foreach" loop, to prevent an accidental endless "while" loop, "maxiter" is default to 1000.  If you want the loop to go until the end regardless, set maxiter to 0.

while (true) display "{result%while:iteration}\n";


The above will display a sequence of numbers from 1 to 1000.  Unlike in "foreach", empty bracket in a "while" condition is not allowed.  At least a dummy condition (true) is required.

The choice between using "while" or "foreach" depends on team culture (or "religion" if you happens to be the team leader, or "standard" if you happens to be the manager.)  There are little differences (if any) in performance as they are both implemented as "while" loop internally.


Previous Page       Next Page

Accsoft Computer Technology Pty Ltd     ABN: 98 065 617 549
PO Box 892, Epping NSW 1710         Level 1, Epping Office Park, 242 Beecroft Rd, Epping NSW 2121, Australia
Tel: Sydney - (02)98691668     National - 1300-881668         Fax: (02)98691866
© Copyright 2003 Accsoft Computer Technology Pty Ltd