Updated 2013-09-01 23:23:07 by RLE

GWM Trace trace can be performed within an Itcl itcl class for tracing member variables being modified, accessed etc. Here is how to do it. The main difference from basic Tcl trace is to use the itcl::scope command to get the full name of the variable for the trace command. As implemented here the trace calls a method of the class giving access to all the elements of the class for debugging.

Trace can also be applied to methods of an itcl class Itcl trace methods.

A trace can also be used as in trace to modify further class member variables (or update Tk widgets or whatever) whenever the variable is modified.
  package require Itcl
  itcl::class testtrace {
    variable member "";#[eval $$name1]
    constructor {} {
      # Here is the trace set to a local variable. Note use of itcl::scope. This calls the method traceit of the class.
      trace add variable [itcl::scope member] write "$this traceit"
    }

    # Here is the method traceit which is called whenever member is modified. Here I output
    # simply the object's name, the variable modified and its new value. You might like a stack trace as well, that is an exercise for the interested reader.
    method traceit {name1 name2 op} { ;# the method which "debugs" the class
      set v [$this info variable $name1 -value]
      puts "Class $this, variable \"$name1\" set to >>$v<<" }
    method setmember {v} { set member $v}
    method getmember {} { return $member }
  }
  set tic [testtrace tickle]  ;# one instance of class testtrace
  set tock [testtrace secondclass]  ;# another instance of class testtrace

  $tic setmember blob  ;# set the member, returns a traceit 
  $tic setmember gurkin
  $tic getmember
  $tic setmember "Open trace"
  $tock setmember "Hello from trace"
  $tic setmember "Open the [$tic getmember] door"

The output from this is:
  Class ::tickle, variable "member" set to >>blob<<
  Class ::tickle, variable "member" set to >>gurkin<<
  Class ::tickle, variable "member" set to >>Open trace<<
  Class ::secondclass, variable "member" set to >>Hello from trace<<
  Class ::tickle, variable "member" set to >>Open the Open trace door<<