I'd like to be able to insure that an action takes place upon exit from a Tcl proc. For example, I need to do something like this:
proc foo {} {
variable var
set saved $var
# some stuff
if {$failed} {
set var $saved
return
}
# more stuff
set var $saved
}
Is there an easy way to do this, so I don't have to repeat the "exit" code at every return? Conceptually:
proc foo {} {
variable var
set saved $var
set do-at-return {set var $saved}
# some stuff
if {$failed} {
return
}
# more stuff
}
Where do-at-return
would be executed whenever foo
exits.
You can probably do complicated things with a "leave" execution trace, but an easier way is to wrap the relevant part of the body in a try/finally statement:
proc foo {} {
variable var
set saved $var
try {
# some stuff
if {$failed} {
return
}
# more stuff
} finally {
set var $saved
}
}