Variables

Introduction

What is a variable? A variable stores an item that can change. e.g. "Car" can be changed to "Cars", 1 can become 567

Variables in programming are indispensable. We can do nothing without variables. So, imagine a program that asks how old a user is. You may wish to print a message depending on the age of the user.

There are many variables types in Gambas, let's start with a few simple ones.

  • Integers - Whole numbers e.g. 1, 14, 897

  • Float - Numbers with decimals e.g. 1.2, 10.115, 0.5, 3.142

  • String - Text e.g. "What is your name?", "Apple"

A variable name must follow some rules:

  • It must never begin by a digit

  • It must never contain any spaces

  • It must never contain any accented character

Let's practice

How to use a variable? Firstly we must declare it, i.e. "create" it before we can use it.

In Visual Basic, it was optional unless you enabled the explicit option.

In Gambas, you must declare all your variables. This is good practice and will help avoid making some mistakes.

This is one way to declare a variable:

Dim MyAge As Integer

You can assign a value like this:

    Dim MyAge As Integer = 25
    Dim nickname As String
    
    nickname = "NewToGambas" 'This is another way to assign a value

Let's have a look at how to print a variable by using the PRINT command:

    ' Gambas module file
    
    Public Sub Form_Open()
    
      Dim nickname As String = "NewToGambas"
    
      Print "My nickname on internet is " & nickname
    
    End

To concatenate (join together) any String variables, we use the & operator.

It's easy, isn't it?

Work with information from the user

To get some data from the user, we will use the InputBox command. http://gambaswiki.org/wiki/comp/gb.form/inputbox. Here is an example:

    ' Gambas module file
    
    Public Sub Form_Open()
    
      Dim nickname As String

      nickname = InputBox("What is your nickname?")
    
      Print "Your nickname is " & nickname
    
    End

When the program arrives at this line:

    nickname = InputBox("What is your nickname?")

It will stop and wait for the data from user and continue when the user presses the Return (or Enter) key.

Last edited by Charlie Ogier 03/11/2018