Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
upvar - do I need to use it?

Posted by admin (Graham Ellis), 16 August 2002
An 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.


Code:
proc double {tommy} {
       upvar $tommy numbah
       set numbah [expr $numbah * 2]
       return 1
       }


set fred 12
set ethel 16
double fred
double ethel
set howidid [double ethel]
puts $fred
puts $ethel
puts $howidid


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.





This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2022: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho