Search code examples
tclglobalprocupvar

How to access a variable defined in proc 'a' from a different proc 'b' which does not call proc 'a'?


I am trying to execute a tcl script which makes exclusive calls to procs a and b. The two procs are not related to each other.

proc a {} {
   set var1 "a"
}

proc b {} {
   # Do something here with: $var1
}

 # script.tcl
 a
 b

I do not have access to the script.tcl as well. When proc 'a' is called, I need to store the var1 somehow such that I can access it later within proc 'b' when it is called. How can I get the value of var1 in proc b? Doesn't seem like I can use 'global' and 'upvar' here?


Solution

  • A simple way is to define the variable in the global scope by preceding the variable name with ::

    proc a {} {
       set ::var1 "a"
    }
    
    proc b {} {
       puts $::var1
    }
    

    Other methods would be to use the global command in each proc or to define the variable in a special namespace of its own.