Reputation: 23
I want to get values of ya0,ya1 using for loop.
But below code is not working.
set ya0 12
set ya1 16
for {set i 0} {$i < 2} {incr i} {
puts "$ya{$i}"
}
Upvotes: 1
Views: 45
Reputation: 13252
You're nearly there.
set ya0 12
set ya1 16
for {set i 0} {$i < 2} {incr i} {
puts [set ya$i]
}
This is slightly simpler but might not be applicable in your code:
set ya0 12
set ya1 16
foreach varname {ya0 ya1} {
puts [set $varname]
}
In both cases, the set
command is used to get the value from a variable whose name isn't known until runtime.
If you want to construct variable names from a root (ya
) and a variable suffix/index (0, 1, ...), an array
can be useful:
set ya(0) 12
set ya(1) 16
for {set i 0} {$i < 2} {incr i} {
puts $ya($i)
}
Sometimes when one does this, what one really wants is a list:
set ya [list 12 16]
for {set i 0} {$i < 2} {incr i} {
puts [lindex $ya $i]
}
# or (better)
foreach val $ya {
puts $val
}
Documentation: for, foreach, incr, lindex, list, puts, set, variable substitution
Upvotes: 5
Reputation: 2661
You can use subst or set to evaluate the value of a variable name.
subst:
set ya0 12
set ya1 16
for {set i 0} {$i < 2} {incr i} {
set varname ya${i}
puts [subst "$$varname"]
}
set:
set ya0 12
set ya1 16
for {set i 0} {$i < 2} {incr i} {
set varname ya${i}
puts [set $varname]
}
output:
12
16
Upvotes: 1