Monday 27 March 2017

Using NEXT to Return from Subroutines

In most of my animated programs you will find a tight main FOR/NEXT loop around line 20, with common subroutines above it, something like this
0 CLS:DIMK(255):K(8)=1:K(9)=2:K(94)=3:K(10)=4:GOTO20
1 IFA-1<0THENNEXT:GOTO22
2 PRINT@A+B*32," ";:A=A-1:NEXT:GOTO22
3 IFA+1>31THENNEXT:GOTO22
4 PRINT@A+B*32," ";:A=A+1:NEXT:GOTO22
5 IFB-1<0THENNEXT:GOTO22
6 PRINT@A+B*32," ";:B=B-1:NEXT:GOTO22
7 IFB+1>14THENNEXT:GOTO22
8 PRINT@A+B*32," ";:B=B+1:NEXT:GOTO22
20 FORZ=1TO65000:PRINT@A+B*32,"X";:REM SOME ENEMY ANIMATION AND COLLISION DETECTION
21 ONK(ASC(INKEY$+"*"))GOTO1,3,5,7:NEXT
22 REM GAME OVER
24 END

This is a simple example of how you can use NEXT to return from subroutines. Since key input in an arcade game can be quite intense, you want to shave off every micro second possible in your main loop. NEXT:GOTO20 might some more kludgy than a clear RETURN but the GOTO20 part is almost never reached and the NEXT returns directly to the first command after the FOR/NEXT loop definition at the beginning of line 20. Using a FOR/NEXT loop saves you a GOTO in every iteration of the loop and all the scanning it requires to find its line number! Not to mention the interpreter having to scan for RETURN (a six letter command) rather than NEXT (a four letter command) for each subroutine call. Also, for each subroutine call you don't have a RETURN and then a NEXT (or GOTO) command to get back to the beginning of the loop. You accomplish both with the one NEXT from your subroutine.



No comments:

Post a Comment