Tcl calling numbered variable

2020-05-03 12:32发布

问题:

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"
}

回答1:

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
}


标签: tcl