Version 4 of Garbage collection

Updated 2002-03-07 04:06:45

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


Arts and Crafts of Tcl-Tk programming