upvar - do I need to use it?
Posted by admin (Graham Ellis), 16 August 2002An example of upvar
The upvar command is vital to most Tcl authors as it allows you to pass
in the name of a variable to a proc, then modify the variable contents
within that proc. It isn't too obvious how it works at first, though, and
it's very different to other programming languages. Here's an
example for you to look through if you're unclear as to how it works.
Scenario - I want to write a proc that doubles the value of an incoming
variable, and puts the result back in the same variable; the value actually
returned by the proc is to be "1" for success (and perhaps 0 for failure in
an extended version?).
When I call my proc, I pass it the name of the variable (so there's no $
character needed), and the variable tommy ends up containing, literally, the
name of the incoming variable - in our example, that's ethel or fred.
The upvar command turns the variable numbah in our proc into the same variable
(and NOT just a copy) as ethel, then as fred, then as ethel again at each
successive call in our example, and thus any changes made to numbah are also
changes made to ethel and fred.
The value returned by double is something quite different to fred, ethel,
tommy or numbah; in one of our calls, we saved a copy of the return value
into howidid to demonstrate the existance of the quite separate return value.
Other Forum Posts
Follow us on ...
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: firstname.lastname@example.org • WEB: http://www.wellho.net • SKYPE: wellho