tcl 变量在不同的命名空间中交互,如何修复

问题描述 投票:0回答:1

在tcl中,我需要获取一些文件,file1,file2,file3,.... fileN,我为每个文件创建每个命名空间,但是每个命名空间中设置的var会影响其他命名空间的var

下面是我的代码:

proc source_file { args } {
global i 
  namespace eval NC{$i} {
   uplevel #0 [list source [uplevel 1 {set args}]]
  }
 incr i
}
set i 1
set A 123
source_file file1.tcl
source_file file2.tcl

文件1.tcl:

set A 456;
puts $A

file2.tcl:

puts $A 

我预计 file2.tcl 的 put 将打印 123,但它打印 456,我的代码错误是什么?

namespaces tcl
1个回答
0
投票

uplevel #0
namespace eval ::
几乎相同; code 参数在全局命名空间中运行。 (区别在于它们管理堆栈的方式;大多数代码不会关心这种差异。)这意味着这两个文件都在“相同”命名空间(全局命名空间)中运行。 在 Tcl 8 中,您需要该文件才能正确显示:

variable A 456 puts $A

要使变量位于正确的命名空间中,您需要使用以下命令调用该文件:
uplevel "#0" [list namespace eval $ns [list source $filename]]
# I put #0 in quotes just to defeat the syntax highlighter here

当然,假设您将名称空间和文件名放在正确的局部变量中。

在 Tcl 9 中,分辨率进行了调整。这将在多个地方更多地破坏此代码,但以修复更多错误的方式......


© www.soinside.com 2019 - 2024. All rights reserved.