O'Reilly logo

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

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

For

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 {
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required