【问题标题】:Tcl variable inside procedure scope issue过程范围内的 Tcl 变量问题
【发布时间】: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


    【解决方案1】:

    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
    }
    

    【讨论】:

      【解决方案2】:

      好吧,看起来像 return [uplevel 1 source $file] 工作!谢谢

      【讨论】:

      • 这读起来更像是评论,最好勾选 Donal 的答案并将其变成正确的评论。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2014-09-20
      • 2021-11-12
      • 2016-08-30
      • 2011-11-21
      • 2011-04-13
      • 2011-10-20
      相关资源
      最近更新 更多