PDA

View Full Version : Change variable increment/decrement into mid-loop?



CuriousOne
- 29th January 2021, 17:09
Hello.
There is a some loop, which monitors keypress, updates display, etc.
Also in loop is variable, which should increase from 1 to 100 and then decrease from 100 to 1.
Is there any way to do it in simple way? without splitting loop into two parts?

HenrikOlsson
- 29th January 2021, 22:12
Something like this perhaps?


Cnt VAR BYTE
Dir VAR BIT

UP CON 1
DOWN CON 0

SomeLoop:
' Monitor keypress
' Update Display
' etc

IF Dir = UP THEN
Cnt = Cnt + 1
ELSE
Cnt = Cnt - 1
ENDIF

IF (Cnt = 100) OR (Cnt = 0) THEN
Dir = ~Dir ' Invert direction
ENDIF

Goto SomeLoop

CuriousOne
- 30th January 2021, 07:43
Yes, thanks!
On spectrum, I was doing this by changing the sign of increment variable, but since in PBP we have no negative numbers....

CuriousOne
- 30th January 2021, 08:09
And yes, CNT=1 should be added in the beginning, or absolutely unexpected behavior will be generated (just tested) :D

HenrikOlsson
- 30th January 2021, 08:38
Regarding negative numbers, as long as both variables are of the same size what you did will work:

Cnt VAR BYTE
Add VAR BYTE

Cnt = 100
Add = -1

Cnt = Cnt + Add ' Cnt now = 99

But if Cnt was a WORD and Add a BYTE then Cnt woul equal 354.