1

New to tcl and trying to understand the "trace add variable" command.

I understand the need to invoke a callback function when a variable is "written" to.

But what is the use of the "read" option? For debugging?

2 Answers 2

1

One example use might be a global counter:

proc init { } {
  set ::globalcounter 0
  trace add variable ::globalcounter read ::gcountUpdate
}

proc gcountUpdate { } {
  incr ::globalcounter
}

proc main { } {
  init
  puts $::globalcounter
  puts $::globalcounter
}
main

I'm sure there are other uses. As you pointed out, debugging.
It could be used for enforcement of variable access by specific procedures.

Sign up to request clarification or add additional context in comments.

Comments

0

One of the uses for read callbacks (which are indeed quite a bit less common than write callbacks) is in linking a Tcl variable to a C variable; the read callback is used to enforce the reading of the C variable and synchronizing the Tcl variable to it. (The write callback would ensure that the update of the Tcl variable gets reflected to the C variable.) Tcl's got a built-in C API that uses this mechanism, though it's using the underlying C API for variable traces rather than the Tcl API that is built on top of it.

You could also use a read callback to make an apparently read-only variable:

trace add variable foo read {apply {args {
    upvar "#0" foo v
    set v "definitely this"
}}}

puts $foo
set foo "that"
puts $foo

I don't recommend using variable traces on local variables. They have a lot more overhead (and internal complexity) than for global/namespace variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.