I have following code where I want to 'continue' if i is less than 5:
1 to: 10 do: [ :i |
i < 5 ifTrue: [ continue ].
'Square of i = ', (i * i) printNl.
]
'continue' in above code is obviously not working. I know that exit
can be used to break out of a loop. But how to continue
? Thanks for your help.
In your case you can simply use ifFalse:
:
1 to: 10 do: [ :i |
i < 5 ifTrue: [
"Any code you need"
] ifFalse: [ 'Square of i = ', (i * i) printNl ].
]
The following code will probably work only in Pharo. (it will not work in GNU Smalltalk, in Smalltalk/X it could work if you use correct modulo. The %
returns complex number):
1 to: 10 do: [ :i |
[ :continue |
i % 5 = 0 ifTrue: [
Transcript show: i; cr.
continue value ].
Transcript
show: i;
show: ', '.
] valueWithExit.
]
The valueWithExit
the implementation in Pharo:
valueWithExit
self value: [ ^nil ]
The meaning:
The receiver must be block of one argument. When it is evaluated and is passed a block, when a value
message is send will exit the receiver block (returning nil
in Pharo).