|
Tcl - global, upvar and uplevel.
In Tcl, variables are "scoped" to the procedure in which they're used. That's a sensible default, since you want to be able to write main applications without the risk of interfering with variables within your procs.
A global command in a proc allows you to refer to a variable in the main code from within a proc. ( No need to declare it global at the top level too)
An upvar command allows you to reference a variable in your calling code from within your proc, and is commonly used for "pass by name" requirements where you're writing a proc that must alter an incoming variable.
The uplevel command allows you to run a piece of code as if it was in the namespace of your calling code and not in your proc - and you can even specify a number of levels of code up or an absolute level number.
Suggestion. Use upvar whenever you need to call by name. Use global sparingly. And think very carefully before you ever use uplevel!
Example:
proc demo {what where} {
global counter
upvar $where hereitis
uplevel incr dc
append hereitis ", UK"
incr counter
puts "Demo run"
return "$what $hereitis"
}
#
set dc 0
set counter 0
set place Melksham
set rz [demo "eat in" place]
puts "function returns: $rz"
puts "place will have UK on the end: $place"
puts "counter is number of calls to demo: $counter"
puts "variable dc has become: $dc"
Runs as
Dorothy:~/oct07 grahamellis$ tclsh uld
Demo run
function returns: eat in Melksham, UK
place will have UK on the end: Melksham, UK
counter is number of calls to demo: 1
variable dc has become: 1
Dorothy:~/oct07 grahamellis$(written 2007-10-24 08:16:15)
Associated topics are indexed under T207 - Tcl/Tk - Procedures and Variable Scope
Some other Articles
Wireless hotel tips - FTP and Skype connections failingReading from another process in Tcl (pipes and sockets)Away or home - which do I prefer?Sorting in Tcl - lists and arraysTcl - global, upvar and uplevel.Square Bracket protection in TclTcl - append v lappend v concatTcl - using [] or {} for conditions in an if (and while)Dark DawnPictures Framed
|
1892 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|