You might have had this problem before:
FOR I=0 TO 3
FOR I=0 TO 7
ENDThe FOR I=0 TO 3 code only runs once, since I becomes 8 after TEST is called.
The way to avoid this is by using local variables. These are special variables in functions that won't affect global variables (variables outside of functions) with the same name.
To use local variables inside functions, VAR* them within the function:
VAR X=4 'doesn't affect the global variable "X"
If you want to access global variables, you must use the variable outside the function first (be sure to VAR your global variables before any DEFs)
X=3 'accesses the local variable since the global one hasn't been used yet
*VAR and DIM are exactly the same; most people use VAR for regular variables and DIM for arrays.
A=7 'local (don't do this, use VAR)
VAR A=7 'local
DEF TEST4 A
DEF TEST5 OUT A
Local variables in SB are pretty weird
Whether a variable in a function is local depends on whether the variable was used outside the function before (on a earlier line)
1: VAR/DIM doesn't actually do anything (VAR I=1 is equivalent to I=1). OPTION STRICT will not change this, it just causes an error if you don't use VAR the first time
2: There can be different variables with the same name (oneglobal version, and multiplelocal versions (inside functions))
PRINT A 'different local variable
TEST 'only sets its own copy of the variable (does nothing)
TEST2 'prints 0
3: During pre-compilation, SB reads the code from top to bottom to look for variables
VAR X 'SB sees this even though it never gets run. (This only affects OPTION STRICT)
X=1 'does not cause an error
4: Variables defined inside of functions are normally local
see example 2
5: Variables outside of functions are always global
A=7 'local variable
TEST 'only sets its own local variable "A"
PRINT A 'prints 3
5: Once a global variable has been defined, all variables after it with that name will be global (including inside DEFs)DEF TEST1
PRINT A 'local
PRINT A '<-global!
'What matters is the order of the DEFs, not the order that functions are run!
TEST2 'prints 4
TEST1 'prints 0
(and in case you're wondering, function arguments and OUT returns are always local)
(also, different slots use completely separate variables, so don't worry about that)