Table of Contents
Tcl includes two commands for looping, the while and for
commands. Like the if statement, they
evaluate their test the same way that the expr does. In this lesson we discuss the
while command, and in the next lesson,
the for command. In most circumstances
where one of these commands can be used, the other can be used as
well.
while
test
body
The while command evaluates
test as an expression. If test is true, the code in body is executed. After the code in body has been executed, testis evaluated again.
A continue statement within
body will stop the execution of the code
and the test will be re-evaluated. A break within body will
break out of the while loop, and execution will continue with the
next line of code after body
In Tcl everything is a command, and everything
goes through the same substitution phase. For this reason, the
test must be placed within braces. If
test is placed within quotes, the
substitution phase will replace any variables with their current
value, and will pass that test to the while command to evaluate, and since the test has
only numbers, it will always evaluate the same, quite probably
leading to an endless loop!
Look at the two loops in the example. If it weren't for the break command in the second loop, it would loop forever.