I am having some problems understanding the use of uplevel in TCL. I am reading Brent Welch’s Practical programming in TCL and Tk and there is an example in uplevel that I cannot understand. Here it 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 please explain it to me? The explanation in the book does not help me enough 🙁
The
uplevelcommand executes a command (or in fact a script) in another scope than that of the current procedure. In particular, in this case it isuplevel 1which means “execute in caller”. (You can also execute in the global scope withuplevel #0, or in other places too such as the caller’s caller withuplevel 2but that’s really rare.)Explaining the rest of that line: the use of the
listhere is as a way of constructing a substitution-free command, which consists of four words,foreach, the contents of theargsvariable, the contents ofvalueListvariable, andbreak(which didn’t actually need to be in braces). That will assign a value from the front ofvalueListto each variable listed inargs, and then stop, and it will do so in the context of the caller.Overall, the procedure works just like the built-in
lassignin 8.5 (assuming a non-empty input list and variable list), except slower because of the complexity of swapping between scopes and things like that.