Breaking Out of While Loops
Use the endloop statement to break out of a while loop. Endloop immediately closes the loop, and execution continues with the first statement following endwhile. For example:
while condition1 do
statementlist1
if condition2 then
endloop;
endif;
statementlist2
endwhile;
If condition2 is true, statementlist2 is not executed in that pass through the loop, and the entire loop is closed.
You can use nested while statements in 4GL, and you can control breaking out of nested loops by using labels, which allow the endloop statement to break to a specific level.
For example:
label1: while condition1 do
statementlist1
label2: while condition2 do
statementlist2
if condition3 then
endloop label1;
elseif condition4 then
endloop label2;
endif;
statementlist3
endwhile;
statementlist4
endwhile;
There are two possible breaks out of the inner loop. If condition3 is true, endloop closes both loops, and control resumes at the statement following the outer loop. If condition4 is true, only the inner loop closes, and execution continues at the beginning of statementlist4.
If you do not specify a label after endloop, only the innermost loop currently active is closed. See the section on endloop in this chapter for additional information.
Examples
Repeat a prompt five times or until a valid answer is given:
answer := ' ';
requests := 0;
while (lowercase(left(answer,1)) != 'y' and
lowercase(left(answer,1)) != 'n' and
requests < 5) do
answer := prompt 'Please answer Y or N:';
requests := requests + 1;
endwhile;
Use the while statement to handle deadlock:
succeed := 0; /* Set to 1 when and if */
/* insert is successful */
tries := 1;
ingerr := 0;
A: while succeed = 0 and tries <= 10 do
insert statement to try to insert
into database
inquire_sql (ingerr = dbmserror);
if ingerr = 0 then
/* Insert completed successfully - */
/* commit the change */
commit;
succeed := 1;
elseif ingerr=4700 then
/* Error due to deadlock - try again */
tries := tries + 1;
else
endloop A;
endif;
endwhile;
if succeed = 1 then
message 'Insert completed successfully';
sleep 3;
else
message 'Insert failed';
sleep 3;
endif;
Last modified date: 08/14/2024