Arrays: Local or Global?

In Liberty BASIC versons 3 and 4, all array values are global. This is true whether the array is Dim'd in the main program or in a sub or function. The same is not true in Run BASIC. Arrays that are Dim'd in the main program do remain GLOBAL throughout the program. Global means the array values are seen both in the main program and in any subs or functions within that main program. Changes to the array are also global.

Print "myArray Dim'd in the main program"
Dim myArray(10)
Print "myArray values assigned in the main program"
    For i = 1 to 10
        myArray(i) = i
    Next i
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print: Print
 
    Call myArrayInSub
 
Print "Changes made to myArray in a sub are global"
    Call ChangeArrayInSub
 
Print "myArray being printed in main program"
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
 
    Print: Print
End
 
Sub myArrayInSub
Print "The original myArray passes into the sub"
Print "The values are global, they remain the same"
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print: Print
End Sub
 
Sub ChangeArrayInSub
Print "The original myArray passes into the sub"
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print
Print "The array values are changed inside the sub"
    For i = 1 to 10
        myArray(i) = myArray(i) * 100
    Next i
Print "The changed myArray"
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print: Print
End Sub

Arrays that are Dim'd in a subroutine or function are LOCAL to that subroutine or function. Local means the values are not seen outside of that sub.

    Call myArrayInSub
 
Print "The array was Dim'd inside a sub, therefore"
Print "the values are only seen inside that sub"
Print "myArray values in the main program"
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print: Print
End
 
Sub myArrayInSub
Print "myArray Dim'd in the main program"
Dim myArray(10)
Print "The array values are assigned inside the sub"
    For i = 1 to 10
        myArray(i) = i
    Next i
    For i = 1 to 10
        Print i;": ";myArray(i)
    Next i
Print: Print
End Sub

It is sometimes desirable to work with a local array inside a sub where the changes are kept local to that sub. Perhaps a certain part of the program needs the array elements alphabetized in some way, yet revert to the original order once the program exits the sub. Still, the Global vs Local status of array elements can become confusing to Liberty BASIC programmers who expect all array values to remain global. To preserve the global status, always be sure the array is Dim'd and Redim'd in the main program and not inside a sub or function.