In Tcl, a control structure is basically just another command. This is one possible implementation of a do ... while
/ do ... until
control structure.
proc do {body keyword expression} {
uplevel 1 $body
switch $keyword {
while {uplevel 1 [list while $expression $body]}
until {uplevel 1 [list while !($expression) $body]}
default {
return -code error "unknown keyword \"$keyword\": must be until or while"
}
}
}
Common for both kinds of do
-loops is that the script named body
will always be executed at least once, so we do that right away. The invocation uplevel 1 $body
means "execute script at the caller's stack level". This way, all variables used by the script will be visible, and any results produced will stay at the caller's level. The script then selects, based on the keyword
parameter, whether to iterate while a condition is true or until it is false, which is the same as iterating while the logical negation of the condition is true. If an unexpected keyword is given, an error message is produced.