You might have had this problem before:
FOR I=0 TO 3
TEST
NEXT
DEF TEST
FOR I=0 TO 7
PRINT "A";
NEXT
END
The
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:
X=2 'global
DEF TEST
VAR X=4 'doesn't affect the global variable "X"
END
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)
Right:
VAR X=2
DEF TEST
X=3
END
Wrong:
DEF TEST
X=3 'accesses the local variable since the global one hasn't been used yet
END
VAR X=2
*
VAR and
DIM are exactly the same; most people use
VAR for regular variables and
DIM for arrays.
more examples
DEF TEST1
A=7 'local (don't do this, use VAR)
END
A=3 'global
DEF TEST2
A=7 'global
END
DEF TEST3
VAR A=7 'local
END
DEF TEST4 A
A=7 'local
END
DEF TEST5 OUT A
A=7 'local
END
original incorrect information
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 (one global version, and multiple local versions (inside functions))
example
DEF TEST
A=2 'local
END
DEF TEST2
PRINT A 'different local variable
END
A=7 'global
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
example
OPTION STRICT
GOTO @SKIP
VAR X 'SB sees this even though it never gets run. (This only affects OPTION STRICT)
@SKIP
X=1 'does not cause an error
4: Variables defined inside of functions are normally local
example
see example 2
5: Variables outside of functions are always global
example
DEF TEST
A=7 'local variable
END
A=3 'global
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)
example
DEF TEST1
PRINT A 'local
END
A=4 'global
DEF TEST2
PRINT A '<-global!
END
'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)