Is there an easy way to unroll the stack in Tcl?
I have this strange problem where I have to get back to a particular stack frame, literally. I can get all the frame information using info command, but to actually get to a particular frame I will have to set some local variables in the each procedure and check them accordingly. I was wondering if there is an easier way.
If you need to get code to do a non-local return (i.e., skipping back several levels) you can do this from 8.5 onwards with the -level option to return. See this example:
proc foo-a {} {
puts a-in
foo-b
puts a-out
}
proc foo-b {} {
puts b-in
foo-c
puts b-out
}
proc foo-c {} {
puts c-in
foo-d
puts c-out
}
proc foo-d {} {
puts d-in
bar
puts d-out
}
proc bar {} {
puts bar-in
return -level 3
puts bar-out
}
foo-a
This works by throwing a special kind of exception; the details are quite hidden. Alternatively, you can also use try and throw if you've got 8.6 or a scripted implementation of them (see the Tcler's Wiki for Tcl code that was used during the discussion of the code in 8.6).
With older Tcl versions, the simplest mechanism is to use return -code 42 and to put some code in place up-stack to catch the custom exception and determine if it is the magic value (42 here; it'll be the result of the catch) and respond appropriately. This can be quite effective, but is also messy. Which is why 8.5 onwards give you tools that are easier to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With