www.gibmonks.com




  Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 7.  Procedures and Scope


The global Command

Global scope is the toplevel scope. This scope is outside of any procedure. Variables defined at the global scope must be made accessible to the commands inside a procedure by using the global command. The syntax for global is:

global varName1 varName2 ...

graphics/tip_icon.gif

The global command goes inside a procedure.


The global command adds a global variable to the current scope. A common mistake is to have a single global command and expect that to apply to all procedures. However, a global command in the global scope has no effect. Instead, you must put a global command in all procedures that access the global variable. The variable can be undefined at the time the global command is used. When the variable is defined, it becomes visible in the global scope.

Example 7-4 shows a random number generator. Before we look at the example, let me point out that the best way to get random numbers in Tcl is to use the rand() math function:

expr rand()
=> .137287362934

The point of the example is to show a state variable, the seed, that has to persist between calls to random, so it is kept in a global variable. The choice of randomSeed as the name of the global variable associates it with the random number generator. It is important to pick names of global variables carefully to avoid conflict with other parts of your program. For comparison, Example 14-1 on page 196 uses namespaces to hide the state variable:

Example 7-4 A random number generator.[*]
proc RandomInit { seed } {
   global randomSeed
   set randomSeed $seed
}
proc Random {} {
   global randomSeed
   set randomSeed [expr ($randomSeed*9301 + 49297) % 233280]
   return [expr $randomSeed/double(233280)]
}
proc RandomRange { range } {
   expr int([Random]*$range)
}
RandomInit [pid]
=> 5049
Random
=> 0.517686899863
Random
=> 0.217176783265
RandomRange 100
=> 17

[*] Adapted from Exploring Expect by Don Libes, O'Reilly & Associates, Inc., 1995, and from Numerical Recipes in C by Press et al., Cambridge University Press, 1988.


      Previous section   Next section
    Top