Looping 102 - For and incr
Tcl supports an iterated loop construct similar to the for
loop in C. The for
command in Tcl takes four arguments; an
initialization, a test, an increment, and the body of code to
evaluate on each pass through the loop. The syntax for the for
command is:
for
start
test
next
body
During evaluation of the for
command, the start
code is evaluated once,
before any other arguments are evaluated. After the start code has
been evaluated, the test
is evaluated. If
the test
evaluates to true, then the body
is evaluated, and finally, the next
argument is evaluated. After evaluating the next
argument, the interpreter loops back to the
test
, and repeats the process. If the
test
evaluates as false, then the loop
will exit immediately.
Start
is the initialization portion of
the command. It is usually used to initialize the iteration
variable, but can contain any code that you wish to execute before
the loop starts.
The test
argument is evaluated as an
expression, just as with the expr
while
and if
commands.
Next
is commonly an incrementing
command, but may contain any command which the Tcl interpreter can
evaluate.
Body
is the body of code to
execute.
Since you commonly do not want the Tcl interpreter's
substitution phase to change variables to their current values
before passing control to the for
command, it is common to group the arguments with curly braces.
When braces are used for grouping, the newline is not treated as
the end of a Tcl command. This makes it simpler to write multiple
line commands. However, the opening brace must be
on the line with the for
command, or
the Tcl interpreter will treat the close of the next
brace as the end of the command, and you will get
an error. This is different than other languages like C or Perl,
where it doesn't matter where you place your braces.
Within the body
code, the commands
break
and continue
may be used just as they are used with
the while
command. When a break
is encountered, the loop exits immediately.
When a continue
is encountered,
evaluation of the body
ceases, and the
test
is re-evaluated.
Because incrementing the iteration variable is so common, Tcl has a special command for this:
incr
varName
?increment?
This command adds the value in the second argument to the variable named in the first argument. If no value is given for the second argument, it defaults to 1.
Example
for {set i 0} {$i < 10} {incr i} { puts "I inside first loop: $i" } for {set i 3} {$i < 2} {incr i} { puts "I inside second loop: $i" } puts "Start" set i 0 while {$i < 10} { puts "I inside first loop: $i" incr i puts "I after incr: $i" } set i 0 incr i # This is equivalent to: set i [expr {$i + 1}]