while(n)

πŸ’– while(n) β€” the Tcl Built-In Commands era πŸ’–

okay bestie, gather round, because while is literally the moment. it's a Tcl built-in command and it's about to run your script over and over and over until the vibes say stop.


✨ NAME ✨

while β€” Execute script repeatedly as long as a condition is met πŸŒ€


✨ SYNOPSIS ✨

while test body

✨ DESCRIPTION ✨

so here's the tea. the while command evaluates test as an expression β€” exactly the same way that expr evaluates its argument. no cap.

the value of that expression must be a proper boolean value, okay? if it's a true value, then body gets executed by passing it to the Tcl interpreter. and then β€” plot twist β€” once body has been executed, test gets evaluated again, and the whole thing repeats until eventually test evaluates to a false boolean value. that's the loop. that's the whole vibe. 🫢

inside body you can run continue commands to terminate the current iteration of the loop (like, skip to the next one bestie, we're moving on πŸ’…), and you can run break commands inside body to cause immediate termination of the while command. bye forever. 😭

and after all that? the while command always returns an empty string. iconic, honestly. gives you nothing back but the journey. ✨

⚠️ okay this is the part where you LISTEN TO ME. test should almost always be enclosed in braces. like, almost always. if it's not, variable substitutions will be made before the while command starts executing β€” which means that variable changes made by the loop body will not be considered in the expression. and that is likely to result in an INFINITE LOOP. πŸ’€πŸ’€πŸ’€ do not do this to yourself.

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. bestie behavior. πŸ‘‘

for an example, try the following script with and without the braces around $x<10:

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

go ahead, run it both ways. one of them slays, one of them is a hostage situation. iykyk. πŸŽ€


✨ EXAMPLE ✨

Read lines from a channel until we get to 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"
}

look at her. counting lines, minding her business, knowing exactly when to stop. main character energy fr fr. 🌟


✨ SEE ALSO ✨


✨ KEYWORDS ✨

boolean, loop, test, while πŸ’–βœ¨πŸŽ€


and that's the whole page, bestie!! πŸ¦‹ this one comes to you from the Tcl manual, and yeah β€” the page is literally named while(n). same energy, same name, same everything. stay looping, stay braced, and never ever forget those curly braces or you WILL be stuck in there forever. mwah. πŸ’…πŸŒΈπŸ’œ

πŸ“¦ where this page comes from