for(3tcl)

πŸ“¦
version 9.0.4 Β· 2 versions
, in debian trixie, ubuntu questing, ubuntu resolute, ubuntu stonking

πŸ’– for β€” the 'For' loop, bestie πŸ’–

so this is a page from the Tcl Built-In Commands manual, and it's about for, and honestly? it's giving C's for statement but make it Tcl. πŸŽ€ come sit with me.


✨ NAME ✨

for β€” the 'For' loop πŸ’…


🌸 SYNOPSIS 🌸

for start test next body

πŸ¦‹ DESCRIPTION πŸ¦‹

for is a looping command, and its whole structure is basically the C for statement's twin. 🫢

So here's the lineup: start, next, and body must be Tcl command strings, and test is an expression string. That's the vibe check on the arguments. βœ…

What happens, in order:

  1. First, for invokes the Tcl interpreter to execute start. πŸ’«
  2. Then it repeatedly evaluates test as an expression.
  3. If that result is non-zero, it invokes the Tcl interpreter on body, then invokes the Tcl interpreter on next, then repeats the loop. πŸ”
  4. The command terminates when test evaluates to 0.

Now the plot twists:

  • If a continue command is invoked within body, then any remaining commands in the current execution of body are skipped β€” no cap. 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. And for returns an empty string. that's it, that's the return value, iconic.

⚠️ OKAY THIS PART. LISTEN. Note that test should almost always be enclosed in braces. If it's 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. ✨ See below for an example: πŸ‘‡

🌈 EXAMPLES 🌈

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

πŸ’€ Either loop infinitely or not at all β€” because the expression being evaluated is actually the constant. or even generate an error! 😭

The actual behaviour will depend on whether the variable x exists before the for command is run, and whether its value is a value that is less than or greater than/equal to ten. And this is because the expression will be substituted before the for command is executed. 🫠

for {set x 0} $x<10 {incr x} {
    puts "x is $x"
}
for {set x 1} {$x<=1024} {set x [expr {$x * 2}]} {
    puts "x is $x"
}

πŸŽ€ SEE ALSO πŸŽ€


πŸ’œ KEYWORDS πŸ’œ

boolean, for, iteration, loop


okay bestie that's the whole page, you ate it, go write some loops πŸ’–

this was Tcl, and the page is for(3tcl) β€” mwah, ily, go forth and iterate. πŸ¦‹βœ¨πŸŒΈ

πŸ“¦ where this page comes from