Question

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 ?)

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top