Problem
The for loop (not foreach) in Tcl has a tedious syntax. For example:
for {set i 0} {$i < 10} {incr i} { puts $i }
That is a lot to type for a simple loop. There must be a better way.
The Solution
While exploring the ubiquitous Tclx package, I found it has just what we need in the form of the loop command whose syntax is:
loop var first limit ?incr? command
Note the fourth parameter, the crement value is optional and default to 1. This command simplifies the above code block as:
loop i 0 10 { puts $i }
Note that the values of i in both cases go from 0 to 9, not 10. Like the for command, the loop command allows the loop counter to skip or to go backward by chaging the increment value:
# Skip count: 0 2 4 6 8 loop i 0 10 2 { puts $i } # Count backward: 10 .. 1 loop i 10 0 -1 { puts $i }
Discussion
Besides making coding loop easier, the loop command also offers another advantage: the limit is evaluated only once, thus improve performance.
The loop command does have one disadvantage over the built-in for command: to use it, you must include the Tclx package. If your script does not use Tclx, this inclusion will incur some small performance penalty up front as the script will have to load Tclx into memory. The Tclx package also increases your script’s memory foot print; depend on your script’s size, the increase could be significant. However, if your script does need Tclx for other reasons, you will get the loop command for free.
Finally, if you want a do .. until or do .. while loop, please read my post titled Does Tcl Has Do Loop?.