namespace is a container for set of identifiers that is used to group variables and procedures. namespaces are available from tcl version 8.0. before the introduction of the namespaces, there was single global scope. now with namespaces, we have additional partitions of global scope.
creating namespace
namespaces are created using the namespace command. a simple example for creating namespace is shown below −
#!/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
when the above code is executed, it produces the following result −
33
in the above program, you can see there is a namespace with a variable myresult and a procedure add. this makes it possible to create variables and procedures with the same names under different namespaces.
nested namespaces
tcl allows nesting of namespaces. a simple example for nesting namespaces is given below −
#!/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
when the above code is executed, it produces the following result −
test1 test2
importing and exporting namespace
you can see in the previous namespace examples, we use a lot of scope resolution operator and it's more complex to use. we can avoid this by importing and exporting namespaces. an example is given below −
#!/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]
when the above code is executed, it produces the following result −
40
forget namespace
you can remove an imported namespace by using forget subcommand. a simple example is shown below −
#!/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::*
when the above code is executed, it produces the following result −
40