问题描述
我需要有关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: $z\n"
执行此命令时,我看不到“ 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 script
和info 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]
可以工作!谢谢