Alaaldeen Eldawie
Alaaldeen Eldawie

Reputation: 7

Tcl calling numbered variable

In Tcl, I assigned values to numbered variables in a loop. how can I call these variables in another loop

for {set colNum 1} {$colNum < 37} {incr colNum} {
    set Col$colNum 0
}   
for {set colNum 1} {$colNum < 37} {incr colNum} {
    puts "$Col$colNum"
}

Upvotes: 0

Views: 50

Answers (1)

Jerry
Jerry

Reputation: 71558

If they are in the same namespace, then you can use set in this way:

for {set colNum 1} {$colNum < 37} {incr colNum} {
    set Col$colNum 0
}   
for {set colNum 1} {$colNum < 37} {incr colNum} {
    puts [set Col$colNum]
}

Usually though, you may want to avoid doing it that way and use arrays instead:

for {set colNum 1} {$colNum < 37} {incr colNum} {
    set Col($colNum) 0
}   
for {set colNum 1} {$colNum < 37} {incr colNum} {
    puts $Col($colNum)
}

Or use upvar to create an alias (I'm using upvar to the global namespace, #0, in the below example):

for {set colNum 1} {$colNum < 37} {incr colNum} {
    set Col$colNum 0
}   
for {set colNum 1} {$colNum < 37} {incr colNum} {
    upvar #0 Col$colNum currentCol
    puts $currentCol
}

Upvotes: 2

Related Questions