1

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?

vandan
  • 13
  • 2

2 Answers2

0

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.

Chris Heithoff
  • 1,787
  • 1
  • 5
  • 14
0

Using variable instead of global offers a bit more flexibility if namespaces are involved

namespace eval n {
    proc a {{value A}} {
        variable var1
        set var1 $value
        return
    }
    proc b {} {
        variable var1
        puts "var1 is <$var1>"
    }
}

n::a
n::b                           ;# => var1 is <A>

namespace eval n {a 42; b}     ;# => var1 is <42>

puts $::var1                   ;# => can't read "::var1": no such variable
glenn jackman
  • 238,783
  • 38
  • 220
  • 352