Declaring Global Variables in Procs


High Maintenance:

Declare the globals to be used in each proc, using individual variables

Example: Two procs with several global variables

proc area {} {
  global height width area
  set area [expr $height * $width]
  }

proc volume {} { global height width depth area set volume [expr $height * $width * $depth] }

Advantage:

Disadvantage:


Low Maintenance:

Use a state array to hold global variables

Example: Two procs with several global values

proc area {} {
  global values area
  set area [expr $values(height) * $values(width)]
  }

proc volume {} { global values volume set volume [expr $values(height) * $values(width) * $values(depth)] if {[catch {testContainerSize $volume}] } {puts "Error: $errorInfo"} }

Advantage:

Disadvantage:

Lower Maintenance:

Create a list of variables to declare global.

Example: Two procs with several global values

set globalList [list values area volume errorInfo errorCode]

proc area {} { global globalList ; eval "global $globalList" set area [expr $values(height) * $values(width)] }

proc volume {} { global globalList ; eval "global $globalList" set volume [expr $values(height) * $values(width) * $values(depth)] }

Advantage:

Disadvantage:


Alternate implementation:

Use a proc with uplevel to declare the globals

Example: Two procs with several global values

set globalList [list values area volume errorInfo errorCode]

proc declareGlobals {list} { global $list uplevel "global [subst $$list]" }

proc area {} { declareGlobals globalList set area [expr $values(height) * $values(width)] }

Advantage:

Disadvantage:


[Contents]
This document was translated by troff2html v0.21 on July 18, 1997.