Inside a subroutine you will need to use variables for various tasks. In portable code you do not want the name you chose for such a variable to clash with a variable of the same name in the main program. To this end you can define a variable as LOCAL.
For example, this is our FLASH subroutine but this time we have extended it to take an argument (nbr) that specifies how many times to flash the LED.
1 2 3 4 5 6 7 8 9 |
Sub FLASH ( nbr ) Local count For count = 1 To nbr Pin(0) = 1 Pause 100 Pin(0) = 0 Pause 150 Next count End Sub |
The counting variable (count) is declared as local which means that (like the argument list) it only exists within the subroutine and will vanish when the subroutine exits. You can have a variable called count in your main program and it will be different from the variable count in your subroutine.
If you do not declare the variable as local it will be created within your program and be visible in your main program and subroutines, just like a normal variable.
You can define multiple items with the one LOCAL command. If an item is an array the LOCAL command will also dimension the array (ie, you do not need the DIM command).
For example:
LOCAL NBR, STR$, ARR(10, 10)
You can also use local variables in the target for GOSUBs.
For example:
GOSUB MySub
...
MySub:
LOCAL X, Y
FOR X = 1 TO ...
FOR Y = 5 TO ...
<statements>
RETURN
The variables X and Y will only be valid until the RETURN statement is reached and will be different from variables with the same name in the main body of the program.
Leave a Reply