This is very useful to know! So, if I keep all my DEF functions at the top of the program, I can avoid having the functions' variables affecting outside variables? I wonder why not just keep all variables inside DEF functions local, or why not let the programmer specify it with a command like COMMON.
FOR I=0 TO 3 TEST NEXT DEF TEST FOR I=0 TO 7 PRINT "A"; NEXT 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:
X=2 'global DEF TEST VAR X=4 'doesn't affect the global variable "X" ENDIf 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 ENDWrong:
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
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
example
see example 2example
DEF TEST A=7 'local variable END A=3 'global TEST 'only sets its own local variable "A" PRINT A 'prints 3
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