Search code examples
variablessettclputs

How to "set" and "puts" variable, which name consists of string and another variable?


I' trying to get a value of variable, which name consists of string "a" and iterator "i" (in this short example I skipped for loop). I was trying to do it with concat and append, with [] and "" and nothing working. Is there any solution for this problem?

set b0 0
set i 0
set a$i $b$i (here is my problem)
puts $a$i

puts should show "0"


Solution

  • To read from a variable whose name is computed, use set with only one argument:

    set a$i [set b$i]
    puts [set a$i]
    

    (There's a real sense in which the $ is a syntactic shorthand for calling this form of set; indeed, the $ syntax is newer.)

    But Use Arrays Instead

    In this case, you are almost certainly better off rewriting your code to use associative arrays.

    set b(0) 0
    set i 0
    set a($i) $b($i)
    puts $a($i)