help-smalltalk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Help-smalltalk] Re: How to exit loops?


From: nice
Subject: [Help-smalltalk] Re: How to exit loops?
Date: Sun, 22 Jun 2008 16:51:41 +0000
User-agent: Thunderbird 2.0.0.14 (Windows/20080421)

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: [...]].





reply via email to

[Prev in Thread] Current Thread [Next in Thread]