nice wrote:
Canol Gokel wrote:
Hello,

Is there a way to exit loops if a condition is met? For example:

1 to: 10 do: [:x |
    x = 3 ifTrue: [
        ...
    ]
]

What should I write instead of three dots to exit the loop if x is equal to 3?


Usual ways to do it:

1) put a return instruction in the ifTrue: block
However, the interpreter will exit the current method and not execute instructions after the to:do:...

2) use some kinf of detect:ifNone: trick
(1 to: 10) detect: [:x | x = 3 or: [... false.]] ifNone: [].


Unusual way:

3) do it with an Exception.
Create a new Exception subclass, say ExitLoop.
Then write:

[1 to: 10 do: [:x | x = 3 ifTrue: [ExitLoop raise] ...]]
    on: ExitLoop do: [:exc | exc return: nil].


Nicolas

Forgot a usual fourth way:

4) use a Stream.

exit := false.
stream := (1 to: 10) readStream.
[ exitLoop or: [stream atEnd]]
        whileFalse: [| x |
                x := stream next.
                x = 3
                        ifTrue: [exit := true]
                        ifFalse: [...]].



_______________________________________________
help-smalltalk mailing list
[email protected]
http://lists.gnu.org/mailman/listinfo/help-smalltalk

Reply via email to