. More Debugging - trace .
[ Previous | Index | Next ]
When you are debugging a program, it's sometimes useful to know when a variable gets changed. The Tcl interpreter supports a method for tracking when and how a variable is accessed. With the trace command, a procedure can be defined to be executed whenever a variable is read, written, or unset. With this command you can determine what proc a variable is modified within, what the value was changed to, and what other variables were at the time.
The trace command executes at the same stack level as the access to the variable. The proc that trace invokes is one stack level lower. Thus, with the uplevel command, a procedure called via a trace can report on the conditions that were set when a variable was accessed.
- trace variable variableName operation procname
- Places a trace on the variable variableName. Whenever variableName is accessed for the operation specified in the operation argument, the procedure procname will be called.
Operation is one of:
- r ...... Read
- w .... Write
- u ...... Unset
A variable can be unset either explicitly with the unset command, or implicitly when a procedure returns, and all of the local variables are released.
When variableName is accessed, procName will be called with three arguments, variableName, elementName and operation. If the variable being accessed is an associative array, then elementName will contain the name of the element being accessed. If variableName is a simple variable, then elementName will be an empty string. Operation is the operation that was done on variableName to invoke the trace action.
- trace vdelete variableName operation procname
- Cancels the trace action for operation on variableName.
- trace vinfo variableName
- Returns information about the traces applied to variableName
--
. Example .
proc traceproc {variableName arrayElement operation} {
set op(w) "Write"; set op(u) "Unset"; set op(r) "Read"
set level [info level]
incr level -1;
if {$level > 0} {
set procid [info level $level]
} else {set procid "main"}
if {![string match $arrayElement ""]} {
puts "TRACE: $op($operation) $variableName($arrayElement) in $procid"
} else {
puts "TRACE: $op($operation) $variableName in $procid"
}
}
proc testProc {input1 input2} {
upvar $input1 i
upvar $input2 j
set i 2
set k $j;
}
trace variable i1 w traceproc
trace variable i2 r traceproc
trace variable i2 w traceproc
set i2 "testvalue"
puts "\ncall testProc"
testProc i1 i2
puts "\nTraces on i1: [trace vinfo i1]"
puts "Traces on i2: [trace vinfo i2]\n"
trace vdelete i2 r traceproc
puts "Traces on i2 after vdelete: [trace vinfo i2]"
puts "\ncall testProc again"
testProc i1 i2
|