Tracing a variable in Tcl
Posted by admin (Graham Ellis), 30 July 2002Do you want to trace a variable in a Tcl program? Be told when it's changed, and perhaps when it's read too? The trace command lets you do this, but you do need top provide a proc to be performed whenever the variable is written / read.
Here's an example:
OK - is that right? Let's add some traces and watch the variable
Good - we can see how it has worked now.
trace variable takes three parameters - the name of the variable to trace, the operation (r for read, w for write), and the name of the command to run whenever the read or write operation happens. You can turn a trace back off using the trace vdelete command.
The proc itself takes three parameters - the variable name, the name of the element (if it's an array element that you're tracing), and a variable telling you if it's a read or a write (you can also use u for unset). In our example, we've added code to allow you trace an array element if there's an element name, and we've also used upvar to get at the value of the variable - probably a requirement that you'll always have in a trace procedure.
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: email@example.com • WEB: http://www.wellho.net • SKYPE: wellho