我刚刚遇到了在 proc 中调用 source 的问题,也许它对某人有帮助。
我有两个测试文件。这是以三种不同的方式sourcetest1.tcl
来源:sourcetest2.tcl
puts "sourcetest1.tcl"
proc mysource_wrong {script} {
source $script
}
proc mysource_right {script} {
uplevel "source sourcetest2.tcl"
}
#source sourcetest2.tcl
#mysource_right sourcetest2.tcl
mysource_wrong sourcetest2.tcl
这是sourcetest2.tcl
:
puts "sourcetest2.tcl"
set l {1 2 3}
puts "outside: $l"
proc doit {} {
global l
puts "doit: $l"
}
doit
source
使用 direct和 with一切都很好mysource_right
,输出在这两种情况下都是:
sourcetest1.tcl
sourcetest2.tcl
outside: 1 2 3
doit: 1 2 3
但是,使用mysource_wrong
,我们得到以下输出:
sourcetest1.tcl
sourcetest2.tcl
outside: 1 2 3
can't read "l": no such variable
while executing
"puts "doit: $l""
(procedure "doit" line 3)
invoked from within
"doit"
(file "sourcetest2.tcl" line 12)
invoked from within
"source $script"
(procedure "mysource_wrong" line 2)
invoked from within
"mysource_wrong sourcetest2.tcl"
(file "sourcetest1.tcl" line 13)
我的解释是 a source
inside aproc
将变量l
放入 的范围,而proc
不是全局范围。这可以通过使用uplevel
like in来避免mysource_right
。