Tcl变量在过程范围内出现问题



我需要帮助处理tcl 中的变量范围

%cat b.tcl

set x 1
set y 2
set z 3

%cat a.tcl

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

当我执行此操作时,我无法读取";x〃:没有这样的可变

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本身或全局范围的堆栈帧内运行。如果您想在其他范围内进行源代码,则需要将uplevel与对source:的调用一起使用

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
}

好吧,看起来return [uplevel 1 source $file]很管用!谢谢

相关内容

最新更新