Variables

There are two kinds of variables in Toy Basic: local and global.

Local variables

Variables have names. Local variable names may contain letters, digits and the underscore character. The following characters are allowed:

  • Letters: A..Z or a..z
  • Underscore: _
  • Digits: 0..9

The first character of a variable name cannot be a digit. Examples of valid local variable names:

  • i
  • MyVariable1
  • _Var10
  • my_variable

Toy Basic is case-insensitive: variable names that differ only by case refer to the same variable.

  • i is the same as I
  • MyVariable1 is the same as MYVARIABLE1 or myvariable1
  • _Var10 is the same as _VAR10 or _var10
  • my_variable is the same as MY_VARIABLE

You can assign values to variables:

int_var = 10
str_var = "string"
You can use variables in expressions and apply operators to them:
alpha = 0.17
sin_3_alpha = sin(alpha * 3)
DrawText(100, 100, "Sine of 3*" & alpha & "=" & sin_3_alpha)
Local variables are visible only within the scope where they are assigned. For example, a variable assigned in the global scope is not visible inside a function:
alpha = 0.17
function PrintAlpha
    DrawText(100, 100, alpha) ' ERROR: alpha is not visible here!
end function
Similarly, a variable assigned inside one function is not visible in another function:
function PrintAlpha()
    alpha = 0.17
    DrawText(100, 100, alpha) ' OK: alpha is assigned here
end function

function PrintSinAlpha()
    DrawText(100, 100, sin(alpha)) ' ERROR: alpha is not visible here!
end function

Global variables

Global variables behave like local variables, except their names begin with the $ prefix. Examples of valid global variable names:

  • $i
  • $MyVariable1
  • $_Var10
  • $my_variable
Global variables are visible everywhere - both in the global scope and inside functions:
$alpha = 0.17

function SetAlpha(alpha)
    $alpha = alpha
end function

function PrintSinAlpha()
    DrawText(100, 100, sin($alpha))
end function

PrintSinAlpha() ' Prints sine of 0.17
SetAlpha(0.28)
PrintSinAlpha() ' Prints sine of 0.28

See also: