while(3tcl)

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

πŸ’– while β€” the Tcl Built-In Commands manual, but make it a group chat πŸ’–

okay bestie, welcome to while(3tcl) β€” she's a classic, she's from the Tcl Built-In Commands collection, and she is literally the blueprint for every loop you've ever loved. πŸ¦‹


✨ NAME ✨

while β€” execute a script over and over again for as long as a condition keeps being met πŸ’…


✨ SYNOPSIS ✨

while test body

✨ DESCRIPTION ✨

so here's the tea πŸ«– β€” while takes test and evaluates it as an expression, exactly the same way expr evaluates its argument. no notes, same energy.

the value of that expression has to be a proper boolean value. if it comes out as a true value, then body gets executed by handing it over to the Tcl interpreter. and then? once body has finished doing its thing, test gets evaluated again, and the whole cycle just keeps repeating until eventually test evaluates to a false boolean value. it's giving commitment, honestly. πŸ‘‘

and because we're flexible in this house:

  • continue commands can be executed inside body to terminate the current iteration of the loop πŸ›‘
  • break commands can be executed inside body to cause immediate termination of the while command πŸ’€

oh and β€” while always returns an empty string. that's it. that's the return value. she gives nothing and that's on purpose. 🌸

⚠️ okay this part matters so listen up bestie β€” test should almost always be enclosed in braces. like, almost always. if you don't brace it, variable substitutions get made before the while command even starts executing, which means variable changes made by the loop body will not be considered in the expression. and what does that lead to? an infinite loop. 😭 not the cute kind. the bad kind.

if test is enclosed in braces, then variable substitutions are delayed until the expression is evaluated β€” which happens before each loop iteration β€” so changes in the variables will actually be visible. πŸŽ€

fr fr, just try the following script both with and without the braces around $x<10 and watch the chaos:

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

✨ EXAMPLE ✨

here's a lil real-world moment πŸ’– β€” read lines from a channel until we hit the end of the stream, and print them out with a line number prepended:

set lineCount 0
while {[gets $chan line] >= 0} {
    puts "[incr lineCount]: $line"
}

ate. no crumbs. ✨


✨ SEE ALSO ✨

the whole loop squad, together at last 🫢


✨ KEYWORDS ✨

boolean, loop, test, while


and that's the page, bestie! this one ships as part of Tcl under the while(3tcl) manual entry β€” go forth and loop responsibly, and brace your test. πŸŒˆπŸ’œπŸ§š

πŸ“¦ where this page comes from