letś say i have a ttk radiobutton , i would like to be able to use it like
ttk::radiobutton .a$b -text -variable a$b
but only the command path ".a$b" works as expected, the variable part "a$b" does not work.
is there a way to make this work?
below is a sample demonstrating the problem:
[lzhou@promote tcl]$ tclsh
% set a 1
1
% set b 0
0
% puts $a$b
10
% set a0 100
100
% puts a$b
a0
% puts ${a$b}
can't read "a$b": no such variable
The call “works” but you have a variable whose name is partially variable. Usually when you're doing that, the easiest way forward is to use an array variable instead.
ttk::radiobutton .a$b -text -variable a($b)
# Note the (parentheses) above!
puts $a($b)
If not that, then the best techniques for reading from the variable either use the single-argument form of set
(which actually predates the $
syntax):
puts [set a$b]
or to make an alias to the variable with a fixed name, using upvar 0
:
upvar 0 a$b theVarAlias
puts $theVarAlias
If you're doing many manipulations on the variable, the second option is superior as aliases are more efficient than looking up a variable name over and over. They do have a little more overhead though so they're not so fast for a one-off use.
We do not recommend reading variables with computed expressions or other weird incantations of expr
or subst
. Those are too tricky in practice. Too many weird edge cases.