【发布时间】:2020-09-01 06:13:42
【问题描述】:
我需要关于 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”:没有这样的变量
【问题讨论】:
标签: variables scope tcl procedure
我需要关于 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”:没有这样的变量
【问题讨论】:
标签: variables scope tcl procedure
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] 工作!谢谢
【讨论】: