1

I have a script like this :

proc subProc1 { } {
    puts $var1
}
proc subProc2 { } {
    puts $var2
}

proc mainProc { args } {
    # Define many variables
    subProc1
    subProc2
    #etc.
}

I would like subProc1 and subProc2 to have variables defined in mainProc. I can pass them as arguments, but it is a lot of argument, I'd like to avoid that.

I tried to use the upvar command, by adding this line to me subProcs :

subProc1 { } {
    upvar $var1 var1 $var2 var2 ;#etc
    puts $var1
    # etc.
}

But I have the "no such variable" error message, and it not nice to have a huge line like this

I just read about namespace but I don't really understand how to use this (plus I am not sure to understand the concept, so is it really adapted to my use case ?)

little-dude
  • 1,544
  • 2
  • 17
  • 33
  • This is a proxy for some real code where this makes sense? If you're just reading, you can pass the value in (efficiently!) as an argument. Tcl passes by copy-on-write reference, which is both efficient and easy to think about at a script level (pretend it always copies, but faster). – Donal Fellows Dec 31 '13 at 21:43

1 Answers1

1

upvar is the right tool for that. The other commands can be emulated with upvar.

But you do a mistake how you call upvar. You have to use the variable name, not it's value (which will throw an "no such variable" error).

upvar var1 var1 var2 var2 ;#...

I'd think about using some different way to store the data, maybe a dictionary or an array?
This would make it easier to pass the variables.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • Thanks. What lead me to this error are the numerous example like these `proc procName { var } { upvar $var var ;#... }`. This kind of things has an interest only if `var` is an array, right ? – little-dude Dec 31 '13 at 17:00
  • 1
    No, you can also pass the name of an ordinary (scalar) variable, if you intend to change the value of that variable like `incr` or `set` does. – Johannes Kuhn Dec 31 '13 at 17:26