在处理未完成时从循环中获取值

Get value from loop while processing is not completed

这个话题之前可能已经(当然)讨论过,但因为我不知道它叫什么,所以我问这个问题...
我的目标是在循环 while 期间获取变量的值,例如 [gets ...] tcl 命令

proc GetValue {var} {

    upvar $var local
    set i 0

    while {$i < 5} {
        set local $i
        incr i
    }
    
    return 0
}

while {[GetValue val] != 0} {
    puts "Line value = $val"
}

我想要这样的结果:

Line value = 0
Line value = 1
Line value = 2
Line value = 3
Line value = 4

一种方法是使用 coroutine to make a generator:

#!/usr/bin/env tclsh
package require Tcl 8.6

proc GetValue {max} {
    set i 0
    set var [yield [info coroutine]]
    while {$i < $max} {
        upvar $var local
        set local $i
        incr i
        set var [yield $i]
    }
    return 0
}

coroutine looper GetValue 5
while {[looper val] > 0} {
    puts "Line value = $val"
}

运行它:

$ tclsh example.tcl
Line value = 0
Line value = 1
Line value = 2
Line value = 3
Line value = 4

这会创建一个名为 loopercoroutine,每次使用变量名称调用它时,都会恢复执行 GetValue,它会设置该变量并 yields循环计数器的当前值返回给调用者,直到它为 5,当它 returns 0 结束时。