Breaking from a do-loop???
Stefan Matthias Aust
sma at 3plus4.de
Sat Jul 1 08:16:20 UTC 2000
At 18:29 30.06.00 -0500, jchludzinski at worldkey.net wrote:
>I'm writing some numerical code and need to know:
>
>How would I accomplish a "break" (a la 'C') from a ST do-loop?
breaking out of a block isn't possible in Smalltalk. You can use "^"
(return) to leave a block but then you'll not only leave the block but also
return from the block's defining method.
Here's a trick to simulate breaking just from a block:
Add the following method to class BlockContext
valueWithExit
^ self value: [:result | ^ result]
Now use
[:exit |
1 to: 10 do: [:i |
i = 5 ifTrue: [exit value: -1]].
10] valueWithExit
and you'll see that this block will return "-1" not "10".
>Use an exception?
might be another solution but frankly, I'd recommend to refactor your
problem so that you either use
i := 1. done := false.
[done or: [i = 10]] whileFalse: [...]
as a loop or that the block is implemented as a single method from which
you can return then.
bye
--
Stefan Matthias Aust // Bevor wir fallen, fallen wir lieber auf
More information about the Squeak-dev
mailing list
|