# How to use local and global variables

- How to use local and global variables
  - The Program:
  - The Code:
  - The Source

A global variable is visible in all methods of a given class.
A local variable is only visible in its particular method.
You may wish to prefix global variables with a character such as "$" to differentiate them.

To make global variables that can be accessed by all the classes of a project, declare them as public in one of your modules (for example, a module called "Global") and then refer to them as properties of that module (for example, Global.myvariable).

## The Program:

Button1 writes "tea with milk" in Label1
Button2 writes "tea with sugar" in Label2
"tea with " is global,
"milk" and "sugar" are local.

## The Code:

    ' Gambas class file

    X AS String

X is global
'it`s NOT allowed to define a value here
'but it can be done in the constructor _new()
'try this instead:
'CONST X AS String = "tea with "

    PUBLIC SUB _new()
      X = "tea with "
    END

    STATIC PUBLIC SUB Main()
      DIM hForm AS Fmain
      hForm = NEW Fmain
      hForm.show
    END

    PUBLIC SUB Button1_Click()
      DIM Y AS String
      Y = "milk"

'Y is local

      Label1.Text= X & Y
    END

    PUBLIC SUB Button2_Click()
      DIM Y AS String
      Y = "sugar"
      Label2.Text= X & Y
    END

'you see the variables X and Y are different:
'each is visible only in its particular method

## The Source

Download