140 GO SUB 500
150 PRINT s
160 x+=2
170 GO SUB 500
180 PRINT s
190 STOP
500  s=0:; This is the start
     of the subroutine
510  FOR y=1 TO x
520    s+=y
530  NEXT y
540 RETURN

When this program is run, see if you can work out what is happening. The subroutine starts at line 500.

A subroutine can happily call another, or even itself (a subroutine that calls itself is recursive), so don't be afraid of having several layers.

LOCAL keyword

LOCAL is a special keyword reserved only for subroutines (see above) and procedures (see below) which ensures that the variables that follow it, are independent of the rest of the program and only valid for the duration of the execution of the subroutine or procedure. Its syntax is as follows:

LOCAL var[=value]

wher var is any variable type (string, numeric or integer) or array and value is the initial (or default) value for said variable. Local arrays1 need to be dimensioned separately after being localised by LOCAL. Multiple variables can be declared in the same LOCAL statement, separated by commas and there can be any number of LOCAL statements in a subroutine or procedure as long as there is enough memory for them.Consider the following example (which won't make much sense until you reach the procedures section further below):

100 PROC x(a(),size,2) TO
    result: PRINT result:STOP
110 DEFPROC x(input(),size,y)
120   LOCAL z():LOCAL tot=0
130   DIM z(size)
150   FOR i=1 TO size:z(i)=input(i)*
    y: NEXT i
160   FOR i=1 TO size: tot+=z(i):NEXT i
170 ENDPROC = tot

The moment that branching back occurs, local variables are released. Consider this silly example (which also demonstrates again the initialisation of local a$):

 10 a$ = "Test"
 20 GO SUB 100
 30 PRINT a$

1 Except integer arrays which are predimentioned


ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.