I'm trying to figure out why in this example the while loop keeps going on indefinitely. The explanation given is
If test is placed within quotes, the substitution phase will replace any variables with their current value, and will pass that test to the while command to evaluate, and since the test has only numbers, it will always evaluate the same
I know that normally you would just use curly braces instead of quotes but I want to understand why double quotes are not used. I also understand that double quotes will substitute the values while the curly braces do not.
set x 0 while "$x < 5" { set x [expr {$x + 1}] if {$x > 7} break if "$x > 3" continue puts "x is $x" } when I print x within the loop I can see it increment so in the case x is 5. I expect the "set x" line to change the value to 6 and will skip the break line. I expect the x > 3 line to pass how come when it checks "$x < 5" that "6 < 5" still gets interpreted as true?
11 Answer
When tcl tries to evaluate the while statement, the first thing it does is split the statement into words, and substitute anything that's in double quotes or square brackets. Data in curly braces is not substituted.
This happens before the while command is called. After this round of substitution, the result of all of the substitutions is passed to the while command as arguments.
Thus, the while statement is given two arguments:
- 0 < 5
- everything inside the curly braces
while sees a static condition that never changes so the loop runs forever.
You should use curly braces so that tcl passes the condition to the while command on each iteration:
while {$x < 5} { ... } With the above, while gets the following arguments:
- $x < 5
- everything inside the curly braces