包的创建和调用
在tcl脚本中,我们可以通过创建和调用包来增强代码的可复用性。
创建包的步骤:
1.在包脚本文件中,首先声明“package provide”,标识当前文件提供了一个包。之后在该文件中完成包的内容
2.通过pkg_mkIndex命令创建pkgIndex.tcl文件,在包所在路径中声明所包含包的名字和版本。
3.通过在auto_path 变量增加包路径,告诉tcl编译器哪里可以找到包。
调用包的步骤:
1.通过package require声明当前脚本需要哪些包。类似于c语言调用头文件。
# 创建一个包
# Register the package
package provide tutstack 1.0
package require Tcl 8.5
# Create the namespace
namespace eval ::tutstack {
# Export commands
namespace export create destroy push pop peek empty
# Set up state
variable stack
variable id 0
}
# Create a new stack
proc ::tutstack::create {} {
variable stack
variable id
set token "stack[incr id]"
set stack($token) [list]
return $token
}
# Destroy a stack
proc ::tutstack::destroy {token} {
variable stack
unset stack($token)
}
# Push an element onto a stack
proc ::tutstack::push {token elem} {
variable stack
lappend stack($token) $elem
}
# Check if stack is empty
proc ::tutstack::empty {token} {
variable stack
set num [llength $stack($token)]
return [expr {$num == 0}]
}
# See what is on top of the stack without removing it
proc ::tutstack::peek {token} {
variable stack
if {[empty $token]} {
error "stack empty"
}
return [lindex $stack($token) end]
}
# Remove an element from the top of the stack
proc ::tutstack::pop {token} {
variable stack
set ret [peek $token]
set stack($token) [lrange $stack($token) 0 end-1]
return $ret
}
# 在编译器中通过pkg_mkIndex命令创建pkgIndex.tcl文件
# 首先切换到包所在路径
% cd /Users/rajkumar/Desktop/helloworld
#通过pkg_mkIndex创建
% pkg_mkIndex . *.tcl
# 包的调用
package require tutstack 1.0
set stack [tutstack::create]
foreach num {1 2 3 4 5} { tutstack::push $stack $num }
while { ![tutstack::empty $stack] } {
puts "[tutstack::pop $stack]"
}
tutstack::destroy $stack
命名空间
命名空间是为了在不同pocedure中避免变量名或者函数名冲突,命名空间常与包一起使用,即一个包提供一个命名空间,包和命名空间名字最好一致。
通过 命名空间名字::变量名/函数名 来调用命名空间中的变量或函数。
若想完全体现命名空间相比全局空间的绝对位置,例如命名空间foo是全局空间的子命名空间,则可通过 ::foo:var调用其中的变量。
注意:再命名空间中申明变量时,不建议用set,否则,如果该变量与global空间变量名字相同时,会导致错误。
01 namespace eval foo {
02 variable stack [list]
03 variable count 0
04 variable params
05 array set params [list var1 value1 var2 value2 var3 value3]
06
07 namespace export push pop
08
09 proc push { args } {
10 variable stack
11 variable count
12 lappend stack $args
13 incr count
14 }
15
16 proc pop {} {
17 variable stack
18 variable count
19 if {[llength $stack] > 0} {
20 set value [lindex $stack end]
21 set stack [lrange $stack 0 end-1]
22 incr count -1
23 return $value
24 } else {
25 error " no more element in the stack"
26 }
27 }
28
29 }
30
31 proc foo::dump {} {
32 variable stack
33 variable count
34 if {[llength $stack] > 0} {
35 puts " There are $count element(s) in the stack:"
36 foreach element $stack {
37 puts " $element"
38 }
39 return 0
40 } else {
41 error " no element in the stack"
42 }
43 }
44
45 namespace import foo::*