while(3tcl)
π 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:
continuecommands can be executed insidebodyto terminate the current iteration of the loop πbreakcommands can be executed insidebodyto cause immediate termination of thewhilecommand π
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 βtestshould almost always be enclosed in braces. like, almost always. if you don't brace it, variable substitutions get made before thewhilecommand 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
- debian trixie: tcl9.0-doc 9.0.1+dfsg-2
- ubuntu questing: tcl9.0-doc 9.0.2+dfsg-1
- ubuntu resolute: tcl9.0-doc 9.0.3+dfsg-1
- ubuntu stonking: tcl9.0-doc 9.0.4+dfsg-1
- Copyright (c) 1993 The Regents of the University of California
- Copyright (c) 1994-1997 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms