[Arjen Markus] There has been much discussion about ''references'' to data in Tcl, in order to build [complex data structures] and such. Inevitably, garbage collection pops up. This page is meant to show that at some mundane level you can let Tcl do the job for you. The script below will create a counter "object" that keeps its internal state hidden. It juggles a bit with the counter object and then throws it away. The essence: the internal state is stored via the [[interp alias]] mechanism that allows extra arguments and the counter itself is destroyed via the [trace] command. ---- namespace eval Counter { variable nextid 0 proc makecounter { name initial } { upvar $name vname variable nextid set vname "[namespace current]::$nextid" uplevel [list trace variable $name u "[namespace current]::deletecounter $vname"] interp alias {} $vname {} [namespace current]::increasecounter $vname $initial incr nextid } proc increasecounter { cmdname current } { set result [expr {$current+1}] interp alias {} $cmdname {} [namespace current]::increasecounter $cmdname $result return $result } proc deletecounter { aliasname counter dummy op } { interp alias {} $aliasname {} # puts "deleted: $counter" } } ;# End of namespace # # Create a counter # Counter::makecounter count1 0 # puts [trace vinfo count1] puts "1? [$count1]" puts "2? [$count1]" # # Copy the counter (not a reference, just a harmless alias) # set count2 $count1 puts "3? [$count2]" # # Deleting the alias has no effect # unset count2 puts "4? [$count1]" # # Deleting the true counter does! # set count3 $count1 unset count1 puts "5? [$count3]" Result: 1? 1 2? 2 3? 3 4? 4 invalid command name "::Counter::0" while executing "$count3" invoked from within "puts "5? [$count3]" " (file "counter.tcl" line 52) ---- Some references: [linked lists] [Tcl and LISP] [complex data structures] ---- The following "'''AI koan'''" (see [http://tuxedo.org/jargon/html/Some-AI-Koans.html] for more) points out a fundamental difference between the Tcl and LISP approaches to when unused memory is reclaimed and the implications this has for what can be a value. One day a student came to Moon and said: "I understand how to make a better garbage collector. We must keep a reference count of the pointers to each cons." Moon patiently told the student the following story: "One day a student came to Moon and said: `I understand how to make a better garbage collector ... (Editorial note: Pure reference-count garbage collectors have problems with circular structures that point to themselves. On the primitive level Tcl avoids that problem by the principle that ''everything is a string'', since strings don't point to anything.) ---- [Arts and Crafts of Tcl-Tk programming]