Search code examples
scopetclproc

variable scope in Tcl inside the procedure


I have below dummy program,

proc main2 {} {          
    set mainVar 100

    proc subproc1 {} {
        puts $mainVar
    }
    subproc1
}

main2

it throws an error can't read "mainVar": no such variable. my question is if I declare a variable (i.e mainVar )in proc isn't that variable should be accessible everywhere inside that proc? why it can't accessible in another proc which is declared inside mainproc proc? please put some light on this


Solution

  • Tcl's procedures do not nest; there is no shared scope at all. The main reason for declaring a procedure inside another one is if you are doing some kind of code generation in the outer procedure (whether of the name, the variable list or the body).

    Now, you can simulate a read-only version like this (simplified version; a full-service variant is a lot more complex):

    proc closure {name arguments body} {
        set vars [uplevel 1 {info locals}]
        set prologue {}
        foreach v $vars {
            upvar 1 $v var
            append prologue [list set $v $var] ";"
        }
        uplevel 1 [list proc $name $arguments $prologue$body]
    }
    
    proc main2 {} {
        set mainVar 100
    
        closure subproc1 {} {
            puts $mainVar
        }
        subproc1
    }
    
    main2
    

    I'll leave making it work correctly with global and arrays (as well as all the other nuances of doing this job properly) as exercises for the reader.