2.3. Using Variables

[<<<] [>>>]

Variables in ScriptBasic store values. These values can be integer, real or string values. The variables are not bound to any type. A variable can hold one type of value at a time and a different on at other types. That is why ScriptBasic is called type-less. Variables are referenced by their names. These names should start with an alpha character, underscore (_), colon (:), or dollar sign ($) and may continue with these characters and numbers. A variable can have any length and all characters are significant. However variable names, just like any other symbol in ScriptBasic are case insensitive. Thus FOO, Foo, fOO and foo mean the same. The following examples are legal variable names:

A
B2
ThisIsAVariable
This_Is_also:a$variable
$perl_style_variable
a$
main::here

The alpha characters and the : _ and $ characters are equivalent in the sense that their usage does not reflect the type or any other feature of the variable. In BASIC languages string variables are usually denoted with a trailing $ character. ScriptBasic does not require this. You can name any variable as you like and store string, integer or real value in that.

A variable can even be an array that holds several variables indexed. These are discussed in array.

In addition to all possible real, integer and string values there is a special value that a variable can hold and this is undef. An undef value means that the variable does not hold any value, in other words it is undefined. All variables that were not assigned any value are undef. When a variable holds a value and is used in an environment where a different type is expected the value is automatically converted.

Example var.bas :

A = "123"
B = A + 1
PRINT B
PRINT
B = A & B
PRINT B
PRINT

Result executing var.bas :

On the line, where addition is used the string value is automatically converted to numeric and the addition was performed on integer values. The variable B will hold an integer value.

Before second PRINT lines the variable B gets a new value again. The operation in this case is concatenation. Because concatenation is a string operation both arguments are converted to be string. The variable A is already a string so there is no need to convert it. The variable B is an integer. This value, and not the variable itself is converted to string and the values are put together.

Variables in ScriptBasic can be local and global. Global variables can be used anywhere in the program, while local variables are available only in the function or subroutine where they are defined. This will be detailed later when I talk about user defined functions and subroutines.

There is a simple name space management in ScriptBasic that helps to avoid name collisions when more than one programmers work on a project. This is detailed in Modules and Name Spaces. From now on it is enough to note that variables like main::a and modu::var are legal variables.


[<<<] [>>>]