Control flow of looping

Martin Drautzburg martin.drautzburg at web.de
Sat Apr 13 11:04:31 UTC 2002


Kamil Kukura <kamk at volny.cz> writes:

> Is it possible in loops such as "true-or-false whileTrue: [ block ]" do
> the iteration repeat or break out similiar to 'break' and 'continue'
> keywords in C?

>From beginner to beginner: I was struck by this one too. The answer
is: there is no break and no continue statement. There are only
methods and which object could possibly perform a break or continue ?
Luckily there is a "return" statement (I don't know which object
performs this).

So you basically have three options:

(1) mimick the break/continue behaviour with nested ifTrue: ifFalse: 
(2) split things up into smaller meaningfully named methods

        while (condition) {
                if (a) continue;
                if (b) break;
                doTheRealWork;
        }


        doTheRealWorkLoop
                " the loop is now a (badly named) method of its own"
                condition whileTrue: [

                        " we use return instead of break: "
                        b ifTrue: [^ self].

                        " this was the continue condition originally: "
                        a ifFalse: [
                                doTheRealWork.
                        ]
                ]

(3) use one of the other methods on collections like collect:
    satisfying: etc

especially (3) is interesting for a beginner. In many cases you do not
really want to "iterate", you just do so, because C offers no other
choice. Experienced smalltalkers say that you never need break or
continue (experienced C programmers say you never need a goto).



More information about the Squeak-dev mailing list