TCL自學筆記-14 定義命名空間
使用命名空間命令創建命名空間。一個簡單的例子,創建命名空間如下圖所示
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
namespace eval MyMath {
variable myResult
}
proc MyMath::Add {a b } {
set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23
puts $::MyMath::myResult
在上面的程序,可以看到有一個變量myResult和程序Add的一個命名空間。這使得創建變量和程序可根據相同的名稱在不同的命名空間。
以上程序也可以用以下定義函數的方法實現。
proc Add {a b } {
return [expr $a + $b]
}
set c [Add 10 23]
puts $c
嵌套的命名空間
TCL允許命名空間的嵌套。一個簡單的例子,嵌套的命名空間如下。
namespace eval extendedMath {
# Create a variable inside the namespace
namespace eval MyMath {
# Create a variable inside the namespace
variable myResult
}
}
set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult
工程師必備
- 項目客服
- 培訓客服
- 平臺客服
TOP




















