Tcl Tutorial Lesson 9

Looping 101 - while loop

Tcl includes three commands for looping, the while, for and foreach commands. Like the if command, they evaluate their test the same way that the expr command does. Here we discuss the while command, and later, the for command. The last command will be treated together with lists, as it iterates over one or more lists.

In many circumstances where one of the commands while or for 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, test is evaluated again.

A continue statement within body will cause the rest to be skipped and execution continues with the next iteration. A break within body will break out of the while loop, and execution will continue after the closing brace.

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!


Examples

set x 1

# This is a normal way to write a Tcl while loop.

while {$x < 5} {
    puts "x is $x"
    set x [expr {$x + 1}]
}

puts "exited first loop with X equal to $x\n"

  Resulting output
x is 1
x is 2
x is 3
x is 4
exited first loop with X equal to 5

Look at the next loop. If it weren't for the break command in the second loop, it would loop forever.

# The next example shows the difference between ".." and {...}
# How many times does the following loop run?  Why does it not
# print on each pass?

set x 0
while "$x < 5" {
    set x [expr {$x + 1}]
    if {$x > 7} break
    if "$x > 3" continue
    puts "x is $x"
}

puts "exited second loop with X equal to $x"

  Resulting output
x is 1
x is 2
x is 3
exited second loop with X equal to 8