Search code examples
tclvar

TCL - set multiple variables to 0


I have many counts variable (ie: count1 count2 count3....)

set count1 0
set count2 0
set count3 0

Instead of typing all on separate lines, is there a shorter way in TCL to just set all the count1.....count100 0

ie: set count1 [list ....]


Solution

  • If you have this many variables close related enough, I'd suggest using an array instead, and you can use a loop with it:

    for {set i 0} {$i <= 100} {incr i} {
        set count($i) 0
    }
    

    That way if you don't need the counts, you can always unset the array and free up some memory pretty easily and quickly.

    If for some reason you cannot use an array instead of a normal variable, then you can still do it like this:

    for {set i 0} {$i <= 100} {incr i} {
        set count$i 0
    }
    

    If the variables are not too much related to each other and there aren't that many of them, you can use lassign and lrepeat like this:

    lassign [lrepeat 4 0] a b c d
    

    In the above, lrepeat will create a list containing the element 0 4 times.