Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch
Table of Contents
Chapter 14. Namespaces
A command is looked up first in the current name space. If it is not found there, then it is looked up in the global namespace. This means that you can use all the built-in Tcl commands inside a namespace with no special effort.
You can play games by redefining commands within a namespace. For example, a namespace could define a procedure named set. To get the built-in set you could use ::set, while set referred to the set defined inside namespace. Obviously you need to be quite careful when you do this.
You can use qualified names when defining procedures. This eliminates the need to put the proc commands inside a namespace block. However, you still need to use namespace eval to create the namespace before you can create procedures inside it. Example 14-2 repeats the random number generator using qualified names. random::init does not need a variable command because it uses a qualified name for seed:
Example 14-2 Random number generator using qualified names.
namespace eval random { # Create a variable inside the namespace variable seed [clock seconds] } # Create procedures inside the namespace proc random::init { seed } { set ::random::seed $seed } proc random::random {} { variable seed set seed [expr ($seed*9301 + 49297) % 233280] return [expr $seed/double(233280)] } proc random::range { range } { expr int([random]*$range) }