Previous section   Next section

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

Table of Contents
Chapter 7.  Procedures and Scope


By default there is a single, global scope for procedure names. This means that you can use a procedure anywhere in your script. Variables defined outside any procedure are global variables. However, as described below, global variables are not automatically visible inside procedures. There is a different namespace for variables and procedures, so you could have a procedure and a global variable with the same name without conflict. You can use the namespace facility described in Chapter 7 to manage procedures and global variables.

Each procedure has a local scope for variables. That is, variables introduced in the procedure live only for the duration of the procedure call. After the procedure returns, those variables are undefined. Variables defined outside the procedure are not visible to a procedure unless the upvar or global scope commands are used. You can also use qualified names to name variables in a namespace scope. The global and upvar commands are described later in this chapter. Qualified names are described on page 198. If the same variable name exists in an outer scope, it is unaffected by the use of that variable name inside a procedure.

In Example 7-3, the variable a in the global scope is different from the parameter a to P1. Similarly, the global variable b is different from the variable b inside P1:

Example 7-3 Variable scope and Tcl procedures.
set a 5
set b -8
proc P1 {a} {
   set b 42
   if {$a < 0} {
      return $b
   } else {
      return $a
P1 $b
=> 42
P1 [expr $a*2]
=> 10

      Previous section   Next section