Navigation:  Tutorials > Beginners Guide to Smalltalk > Control Flow >

Looping

Previous pageReturn to chapter overviewNext page

As you might expect by now, Smalltalk uses messages to perform looping operations too.

10 timesRepeat: [ teresa moveRight: 10 ].

5 timesRepeat: [ simon growBy: 5 ].

 

The #timesRepeat: message sent to an integer will cause its parameter block of code to be executed that number of times. You can have quite a bit of fun with loops and limited animation in the Playground:

[ charlie position x > 0 ] whileTrue: [ charlie moveLeft: 10 ]

 

This is interesting; here we have two blocks at work. The #whileTrue: message is sent to a block of code that is expected to answer a boolean result. If this is true then the parameter block is executed. This process is repeated until the receiver block answers false. You've probably guessed already that there is also a similar #whileFalse: message:

[ teresa rotation >= 90 ] whileFalse: [ teresa rotateBy: 10 ].

 

Tip: you are probably noticing that the Playground window "flashes" while we are performing these bits of animation. This is because the Playground was not designed for smooth animation which really needs to be implemented using a process known as "double buffering". You can certainly implement smooth animation using Dolphin, it's just that the Playground has been kept as simple as possible to aid understanding. Note, also, that the speed of each animation step has been deliberately slowed down so you can see it happening. Dolphin is capable of drawing "frames" much faster than you see here.

That are two shortcut versions of #whileTrue and #whileFalse that can just be sent to a block of code to cause it to execute repeatedly while it answers true or false respectively. These messages do not require any parameters:

[ teresa moveLeft: 5.

teresa position x > simon position x ] whileTrue.

 

Here we see that the value answered from a code block when it is executed is that of the last expression in the block. The above example moves teresa left and then compares its new horizontal position with that of simon. The result of this comparison is returned as the final result from the block and the #whileTrue message is designed to repeat until this eventually yields false.