A simpler Tcl For Loop

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?.

4 thoughts on “A simpler Tcl For Loop

  1. sau

    Somehow it doesn’t show the “less than” symbol. Anyways, $i should be “less than” instead of “more than”.

  2. wedding favors uk

    I every time used to read piece of writing
    in news papers but now as I am a user of web thus from now I am using net for articles or reviews,
    thanks to web.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s