Pedro Cardoso
Pedro Cardoso

Reputation: 89

Tcl - How to read a nested variable from inside a procedure

I am trying to do the following:

set myvar_key something
set a myvar
proc test {} {
  # I am expecting mylocal_var to be "something", but it errors
  set mylocal_var [set ${::a}_key]
}

# The proc is called like this
test

Thanks in advance, Pedro

Upvotes: 0

Views: 188

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137767

In these sorts of scenarios, it tends to be easier to use upvar to make a local alias for a variable in another scope. Yes, you can do trickery with set and such, but it tends to be harder to use, especially in real code. Once you've done the upvar, the local name is just another (highly efficient) way of accessing the named variable in another scope.

set myvar_key something
set a myvar
proc test {} {
     # The #0 is quoted *just* for Stack Overflow's highlighting!
     upvar "#0" ${::a}_key mylocal_var
}

If you were willing to rearrange your variables, you could instead do:

set key(myvar) something
set a myvar
proc test {} {
    global a key
    set mylocal_var $key($a)
}

But that does change what the main variable is so it isn't suitable in all cases. And you can do hybrids:

set key(myvar) something
set a myvar
proc test {} {
    upvar "#0" key($::a) mylocal_var
}

Upvotes: 3

JHBonarius
JHBonarius

Reputation: 11291

You're almost there, but just missed something. As your code already shows, a is in the global namespace, thus you need ::a. Same is true for myvar_key, thus you need to do

set myvar_key something
set a myvar
proc test {} {
  set mylocal_var [set ::${::a}_key]
  puts $mylocal_var
}
test

prints "something"

Upvotes: 2

Related Questions