[Top][All Lists]

[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:47:09 +0000
User-agent: Thunderbird (Windows/20080421)

Canol Gokel wrote:

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


reply via email to

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