Intermediate Level: DEF PROC, PROC, END PROC
We look at Procedures in NextBASIC.
As we found in our sub-routines example, you GOSUB to a specific line number, and RETURN when the code in that section has finished - They're great for when you have a repeating section of code you need to call within a program.
Procedures are a bit more clever than that. Firstly, you can give them meaningful names instead of using line numbers, and they allow variables to be passed back and forth.
Using a procedure to repeat a section of code
To start, lets not use any variables, so in this instance, the procedure will be used to do something that's probably going to be repeated quite a bit in the program. You don't really need a procedure for this, but it demonstrates the principals of a routine that can be called over and over again.
10 PRINT "HELLO"
20 helloagain
30 goto 20
100 DEF PROC keypress ()
110 IF INKEY$ = "" then goto 110
120 PRINT INK RND*7 "Hello Again"
130 BEEP 0.05,30
140 END PROC
Every time you press any key, the computer prints "Hello Again" in a random colour until you hit BREAK to clear the program loop.
Passing variables into the procedure
Let's create a very simple BASIC program example that prints out a line of text in different colour and paper combinations.
10 Let t$="Hello There "
20 FOR i=0 TO 16
30 PROC type t$,i
40 NEXT i
100 DEFPROC write (w$, a); w$ is the text we put into the procedure, followed by the ink colour i.
110 PRINT INK a PAPER b w$
120 ENDPROC
You can see we set up variables i for ink, p for paper, and T$ for the text. When we set up our procedure, we used different variable names, a b and w$ respectively, but the program knew exactly what to do, as it passed the values that we gave the procedure using the PROC type command.
That shows passing variables into the procedure. What if you want to pass a variable back into the main program?
Passing variables out of the Procedure
Let's do a simple calculator procedure, that doubles a number that you enter. Yes, we could do that in the main basic program, but this is simply a demonstration to show variable passing.
10 PRINT "Double a number...."
20 INPUT "Enter a value:" n
30 double n
40 PRINT v " is double the value of " n
100 DEFPROC double (v)
110 LET v=v+v
120 ENDPROC =v
Here, the value of n that was used for the input is retained, with a new variable v being returned for use in the main program. It's a bit of a waste to ue a procedure like this, but the example is simplistic to demonstrate how it works. Use procedures for slightly more complicated tasks.