Tcl - 命名空间

命名空间是一组标识符的容器,用于对变量和过程进行分组.命名空间可从Tcl 8.0版获得.在引入名称空间之前,存在单一的全局范围.现在有了命名空间,我们有了全局范围的附加分区.

创建命名空间

使用命名空间命令创建命名空间.下面显示了创建命名空间的简单示例;

#!/usr/bin/tclsh

namespace eval MyMath {
  # Create a variable inside the namespace
  variable myResult
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
  set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23

puts $::MyMath::myResult

执行上述代码时,会产生以下结果 :

33

在上面的程序中,你可以看到有一个带变量的命名空间 myResult 和一个过程添加.这样就可以在不同的命名空间下创建具有相同名称的变量和过程.

嵌套的Namesp aces

Tcl允许嵌套命名空间.嵌套命名空间的简单示例在下面和下面给出;

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
}

namespace eval extendedMath {
   # Create a variable inside the namespace
   namespace eval MyMath {
      # Create a variable inside the namespace
      variable myResult
   }
}
set ::MyMath::myResult "test1"
puts $::MyMath::myResult
set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult

执行上述代码时,会产生以下结果 :

test1 
test2

导入和导出命名空间

您可以在之前的命名空间示例中看到,我们使用了大量的范围解析运算符,并且使用起来更复杂.我们可以通过导入和导出名称空间来避免这种情况下面给出一个例子 :

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}

namespace import MyMath::*
puts [Add 10 30]

当执行上面的代码时,它产生以下结果 :

40

忘记命名空间

您可以使用删除导入的命名空间忘记子命令.一个简单的例子如下所示 :

#!/usr/bin/tclsh

namespace eval MyMath {
   # Create a variable inside the namespace
   variable myResult
   namespace export Add
}

# Create procedures inside the namespace
proc MyMath::Add {a b } {  
   return [expr $a + $b]
}
namespace import MyMath::*
puts [Add 10 30]
namespace forget MyMath::*

执行上述代码时,会产生以下结果 :

40