Version 0 of Pass by reference

Updated 2002-09-19 16:58:19

KPV After having read a criticism of tcl that it doesn't have true pass by reference--you have to fake it with using upvar--I thought I'd write a tcl-only clone of proc called xproc that will automatically give you pass by reference ala C++ syntax. Specifically, you say proc myproc {arg1 &arg2 arg3 &arg4} {body} and arg2 and arg4 will automatically be pass by reference.

 proc xproc {pname arglist body} {
     set newarglist {}
     set ups ""
     foreach arg $arglist {
         if {[string match "&*" $arg]} {
             set arg [string range $arg 1 end]
             append ups "upvar 1 \$_$arg $arg;"
             lappend newarglist _$arg
         } else {
             lappend newarglist $arg
         }
     }
     set newbody [concat $ups $body]
     set newproc [list proc $pname $newarglist $newbody]
     eval $newproc
 }

Here's a sample usage:

 xproc myproc {&arr} {
     foreach n [array names arr] {
         puts "arr($n) => $arr($n)"
     }
 }
 array set myarray {1 one 2 two 3 three}
 myproc myarray