Basically, what I'm doing is
set i 0
set log_$i "blah blah"
puts $log_$i; # expecting to see "blah blah"
this returns the error:
can't read "log_": no such variable
I've tried all different kinds of grouping, nothing seems to work
The issue you've got is that $
-substitution stops when it encounters a $
(and lots of other punctuation too).
To make what you're doing work, you'd do this to read the variable (using the single-argument form of the set
command):
puts [set log_$i]
That compiles to exactly the sort of bytecode that you'd expect.
BUT…
Don't do it that way if you can avoid it.
Any time you're thinking about constructing variables like that, you're more likely to be in need of using arrays:
set i 0
set log($i) "blah blah"
puts $log($i)
That does work. And if you're really in need of working with a variable whose name is constructed, it's often easier to construct a (typically local) variable alias to it like this:
set i 0
upvar 0 log_$i v
set v "blah blah"
puts $v
The upvar
command is tricky stuff, and allows for all sorts of really powerful techniques. It also makes the local aliases to variables very efficient (though this alias does not include looking up the variable each time; you'll need to rerun upvar
if you want the alias to point to something else).
Another way of doing is
==>tclsh
% set i 0
0
% set log[set i] bb
bb
% puts "[set log[set i]]"
bb