You are here: Surpac Concepts > Macros > TCL > Scope of TCL variables
GEOVIA Surpac

Scope of TCL variables

The scope of a variables and procedures defines where & when the variable or procedure can be used. This is of particular importance when you start using procedures in your TCL scripts.

By default procedures are global in scope. That is once defined, a procedure can be used, i.e. called from, any other procedure. In all the examples seen so far you will note that procedures are defined first before they are used. The TCL interpreter requires that procedures and variables be defined before they are referenced. The only exception to this is when variable names are passed to procedures and the procedure assigns a value to the variable.

Any variable that is defined outside a procedure has global scope. That is, once defined it can be used until it is unset. This does not mean that you can automatically access these global variables from inside a procedure. This is deliberately discouraged unless you use the global command to access global variables from within a procedure. One important point to note here is that the global variable need not exist when a procedure that refers to is executed. The procedure can set a value for the variable and thus cause that global variable to appear in the global scope.

There are not many instances where you should contemplate using global variables as they generally lead to poor programming practice. However there are some occasions where you should use them hence this discussion.

Example: Using a global variable in a procedure

proc myproc {a} {
  global myglobal
  set myglobal $a
}
myproc 5
puts "myglobal=$myglobal"

Output: myglobal=5

The example above shows how the myglobal variable does not exist until it is assigned a value by the myproc procedure.

Variables defined inside a procedure are local to that procedure only and cease to exist when that procedure terminates. This is good because it means that large arrays in particular that may be used inside a procedure automatically get unset when a procedure terminates, releasing the memory that was used for storing those arrays.