How To

Is it possible to break or continue a loop?

1

Jeanmilost 2020-02-27 12:13

Hello,

I'm originally a c++ coder :) In c++, there are 2 instructions very useful to control a loop:
- the break keyword allows to break a loop and go out of it
- the continue keyword allows to skip the current iteration and continue with the next one

Are such instructions existing in Basic?


Timo 2020-02-27 12:42 (Edited)

For "break" I planned EXIT, but it's not yet implemented because it was more complicated than expected. Hm, it's on the TO DO list since 2017 :O https://github.com/timoinutilis/lowres-nx/issues/29

Currently I'm not very active on this project...


nwallen 2020-02-27 12:54

For break I use a break sub on the outside of the loop. Not too elegant as if i needed it for multiple loops I need to keep coming up with new names.
Same can work for continue.

FOR I = 1 TO 5
IF I = 3 then gosub BREAK
NEXT I
BREAK:
print(I)


Roger Davis 2020-02-27 12:57

Perhaps there is a POKE that could be used for "break"? 🤔 I seem to remember using a POKE many years ago on the Commodore C64 which caused such a thing to occur. There was also a keyboard command which could be included into your BASIC code to cause a break, although I think that one caused the program to stop running completely. @Timo, perhaps you included such a POKE in the development of Lowres NX and have since forgotten about it? 🤔 Maybe as part of the debugging system?


Timo 2020-02-27 13:38

nwallen: Please use GOTO instead of GOSUB. Gosub uses a stack to be able to return. Using it wrongly may result in an out of memory error when the stack is full.

Roger: No, the interpreter runs outside of the virtual hardware, so POKE won't help in this case.


was8bit 2020-02-27 14:29

GOTO a label outside the loop works

and a contional check can allow stuff to be skipped or processed each iteration...

FOR I
IF condition THEN
(process this iteration)
END IF
NEXT I


was8bit 2020-02-27 14:36

Another variation for BREAK out an iteration...

I=0
CHECK=0
WHILE CHECK=0
INC I
(Process stuff)
IF condition THEN CHECK=1
WEND

This allows multiple different ways to discontinue the WHILE WEND loop by letting any condition check set CHECK=1..

The reverse is also possible

CHECK=99
WHILE CHECK <>0
CHECK=0
IF condition THEN INC CHECK
WEND

This variation allows to only do the loop IF needed, as well as you can take a peek at CHECK with PRINT or NUMBER to debug issues if the loop gets stuck...


Jeanmilost 2020-02-27 14:54

Thank you very much for all these answers, full of good ideas. In fact without specific instructions I planned to workaround using subprograms, where the return instruction in the subprogram will act as a continue, and the return inside the loop itself will act as a break. I just wanted to know if there was existing and more elegant instructions to achieve these effects before doing that :)


Log in to reply.