Version 6 of for

Updated 2003-09-29 19:46:41

for - "For" loop

for start test next body for start test next body http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/for.htm

For is a looping command, similar in structure to the C for statement. The start, next, and body arguments must be Tcl command strings, and test is an expression string. The for command first invokes the Tcl interpreter to execute start. Then it repeatedly evaluates test as an expression; if the result is non-zero it invokes the Tcl interpreter on body, then invokes the Tcl interpreter on next, then repeats the loop. The command terminates when test evaluates to 0. If a continue command is invoked within body then any remaining commands in the current execution of body are skipped; processing continues by invoking the Tcl interpreter on next, then evaluating test, and so on. If a break command is invoked within body or next, then the for command will return immediately. The operation of break and continue are similar to the corresponding statements in C. For returns an empty string.

official reference

Note: test should almost always be enclosed in braces. If not, variable substitutions will be made before the for command starts executing, which means that variable changes made by the loop body will not be considered in the expression. This is likely to result in an infinite loop. If test is enclosed in braces, variable substitutions are delayed until the expression is evaluated (before each loop iteration), so changes in the variables will be visible. For an example, try the following script with and without the braces around $x<10:

 for {set x 0} {$x<10} {incr x} {
   puts "x is $x"
 }

(From: TclHelp) See also: TclHelp


The bracing of test will result in expr parsing the contents. But in braced expressions, expr does not tolerate operators to be passed in as variables. If you want to do that, call an explicit expr without braced condition (but inside brackets and braces, as explained above), so the Tcl parser substitutes that in each loop repetition:

 set op "<"
 for {set x 0} {[expr $x $op 10]} {incr x} {puts "x is $x"} ;#RS

In some situations, using a foreach with a fixed list is more convenient than a for, compare:

 foreach i {1 2 3 4 5} {...
 for {set i 1} {$i <= 5} {incr i} {...

or, instead of unrolling a range, you can wrap one for for sugaring:

 proc range {from "to:" to} {
        set res [list]
        for {set i $from} {$i<=$to} {incr i} {lappend res $i}
        set res
 }
 foreach i [range 1 .. 5] {...

This is, however, slower than for.

Foreach generally is better style in non-numeric looping. Those accustomed to writing in C sometimes find this a difficult habit to learn, because they think of an indexed array where a Tcl coder writes simply

 set color_list "red blue umber mauve"
 foreach color $color_list {...}

---

See also:


Tcl syntax help - Arts and Crafts of Tcl-Tk Programming - Category Command from Tcl