Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 6.  Control Structure Commands


The for command is similar to the C for statement. It takes four arguments:

for initial test final body

The first argument is a command to initialize the loop. The second argument is a boolean expression that determines whether the loop body will execute. The third argument is a command to execute after the loop body:

Example 6-13 A for loop.
for {set i 0} {$i < 10} {incr i 3} {
   lappend aList $i
set aList
=> 0 3 6 9

You could use for to iterate over a list, but you should really use foreach instead. Code like the following is slow and cluttered:

for {set i 0} {$i < [llength $list]} {incr i} {
    set value [lindex $list $i]

This is the same as:

foreach value $list {

      Previous section   Next section