Version 1 of use_refs

Updated 2005-12-15 11:34:40 by suchenwi

Richard Suchenwirth 2005-12-15 - A colleague wanted some sugar for upvar variables to pass by reference, but as the use of xproc prevented the names of such procedures to end up in tclIndex, we cooked up (it was lunch) this minimally invasive version:

 proc use_refs {{char &}} {
    foreach v [uplevel 1 {info locals}] {
        if [string match $char* $v] {
            uplevel 1 "upvar 1 \${$v} [string range $v 1 end]"
        }
    }
 }

That's all. This command is preferrably called first inside a proc, and upvars all arguments that begin with a specific character, the default being "&" - it runs code like

 upvar 1 ${&foo} foo

in the caller's scope. Testing:

 proc test_refs {a &b} {
    use_refs
    puts a=$a,b=$b
    set b new_value
 }
 % set bar 42
 42
 % test_refs foo bar
 a=foo,b=42

So the values of a and b are readable...

 % set bar
 new_value

...and the side effect of changing b in the caller did also happen.


Arts and crafts of Tcl-Tk programming