How to use variables

Before using a variable, you must first tell thinBasic how you are going to use it. This is done in a declaration statement where the variable's scope and type are made known. Scope refers to the variable's reputation, so to speak.

It can be known ...

  • Only for a short period of time
  • Only to a certain group
  • To everyone all the time

If the variable is global, it can be used in any part of your script. If it is local to a subroutine (or function), it is only known for a short period of time when that subroutine is running. After the subroutine is finished, the variable is forgotten (removed from computer memory). If it is static to a subroutine, the variable is known only in that subroutine but is not forgotten after the subroutine is finished running. ThinBASIC intuitively marks scope using the keywords GLOBAL, LOCAL and STATIC. There is also a universal DIM keyword, which defines a variable as LOCAL when used inside a subroutine or GLOBAL when used outside of any subroutine.

The general syntax is:

<scope> <variableName> AS <type>
Here are a few examples of numeric variable declarations:
LOCAL  countA AS BYTE    ' -- Local variable represented by a 8 bit integer
STATIC countB AS INTEGER ' -- Static variable represented by a 16 bit integer
GLOBAL countC AS LONG    ' -- Global variable represented by a 32 bit integer
Here are a few string declarations:
LOCAL  nameA AS STRING      ' -- Local dynamic string variable
STATIC nameB AS STRING * 10 ' -- Static fixed length string variable for storage of 10 characters
GLOBAL nameC AS ASCIIZ * 10 ' -- Global null terminated string variable for storage of 
                            ' -- 9 characters and 1 null character
Unlike some other languages, ThinBASIC always automatically initializes the variables. That means thinBasic sets numeric variables to zero and string variables to an empty string. However, you can force custom initialization during the declaration using the following simple assignment:
LOCAL age   AS LONG   = 5
LOCAL name  AS STRING = "James"

Then, to later use such a variable, all you have to do is refer to its name:
LOCAL numberOfFruit AS LONG
LOCAL numberOfOranges AS LONG = 2
LOCAL numberOfApples AS LONG = 3

numberOfFruit = numberOfOranges + numberOfApples

Obviously, numberOfFruit would equal 5 after the statement, "numberOfFruit = numberOfOranges + numberOfApples."