Unable to understand top level command in TCL

I'm having some problems understanding the use of the TCL layer. I am reading Brent Welch Practical Programming in TCL and Tk, and there is an example at a level that I cannot understand. There he is:

proc lassign {valueList args} { if {[llength $args] == 0} { error "wrong # args:lassign list varname ?varname...?" } if {[llength $valueList] == 0} { #Ensure one trip through the foreach loop set valueList [List {}] } uplevel 1 [list foreach $args $valueList {break}] return [lrange $valueList [llength $args] end] } 

Can someone explain this to me? The explanation in the book does not help me :(

+6
source share
2 answers

The uplevel command executes a command (or actually a script) in a different scope than in the current procedure. In particular, in this case it is uplevel 1 , which means "execute in the caller". (You can also execute in the global scope using uplevel #0 or in other places, such as the caller with uplevel 2 , but this is very rare.)

Explanation of the rest of this line: using list here is a way to build a command without replacement, which consists of four words, foreach , the contents of the variable args , the contents of the variable valueList and break (in fact, this should not have been in braces). This will assign a value from the front of the valueList each variable specified in args and then stop, and this will be done in the context of the caller.

In general, this procedure works just like the built-in lassign in 8.5 (assuming a non-empty input list and a list of variables), except for a slower one due to the complexity of exchanging between areas and such things.

+6
source
 proc a {} { set xa uplevel 3 {set x Hi} puts "x in a = $x" } proc b {} { set xb a puts "x in b = $x" } proc c {} { set xc b puts "x in c = $x" } set x main c puts "x in main == $x" 

here the innermost method a will be at level 0 and b at level, c at level 2, and the main program will be at level 3, so in proc a, if I change the value of the level, then I can change the value of the variable x of any proc - this is a , b, c or main proc from method "a" itself. try changing the level to 3,2,1,0 and see the magic path.

+3
source

Source: https://habr.com/ru/post/920765/


All Articles