过程范围内的 Tcl 变量问题

Tcl variable inside procedure scope issue

我需要有关 tcl 中变量作用域的帮助

%猫b.tcl

set x 1
set y 2
set z 3

%猫a.tcl

proc test {} {
  source b.tcl
}
test
puts "x : $x, y: $y, z: $z\n"

当我执行这个时,我无法读取“x”:没有这样的变量

好的看起来 return [uplevel 1 source $file] 有效!谢谢

source 命令几乎与此过程完全相同:

proc source {filename} {
    # Read in the contents of the file
    set f [open $filename]
    set script [read $f]
    close $f

    # Evaluate the script in the caller's scope
    uplevel 1 $script
}

(参数解析、通道的配置方式以及 info scriptinfo frame 等事物的设置方式存在细微差别,这使得真实的事情变得更加复杂。他们不'改变上面的整体印象,真正的代码是用C实现的。)

特别是,脚本 运行 在调用者的堆栈帧中,而不是在 source 本身或全局范围的堆栈帧中。如果您想在其他范围内获取源代码,则需要在调用 source:

时使用 uplevel
proc test {} {
    # Run the script globally
    uplevel "#0" [list source b.tcl]
}

文件名 没有 Tcl 元字符的情况下(您自己的代码通常如此),您可以马虎:

proc test {} {
    # Run the script in the caller's scope
    uplevel 1 source b.tcl
}