while循环中{}和""的区别

Difference between {} and "" in while loop

我想弄清楚为什么在此示例中 while 循环会无限期地继续下去。给出的解释是

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

我知道通常您只会使用大括号而不是引号,但我想了解为什么不使用双引号。我也明白双引号会替换值,而花括号不会。

set x 0
while "$x < 5" {
    set x [expr {$x + 1}]
    if {$x > 7} break
    if "$x > 3" continue
    puts "x is $x"
}

当我在循环中打印 x 时,我可以看到它递增,因此在 x 为 5 的情况下。我希望 "set x" 行将值更改为 6 并跳过断行。我希望 x > 3 行通过,当它检查“$x < 5”时,“6 < 5”仍然被解释为 true 怎么会这样呢?

当 tcl 尝试计算 while 语句时,它做的第一件事是将语句拆分为单词,并替换双引号或方括号中的任何内容。大括号中的数据不会被替换。

这发生在调用 while 命令之前。在这一轮替换之后,所有替换的结果作为参数传递给 while 命令。

因此,while 语句有两个参数:

  1. 0 < 5
  2. 花括号内的所有内容

while 看到一个永不改变的静态条件,因此循环永远运行。

您应该使用大括号,以便 tcl 在每次迭代时将条件传递给 while 命令:

while {$x < 5} { ... }

根据以上内容,while 得到以下参数:

  1. $x < 5
  2. 花括号内的所有内容