Variables

Introduction

What is a variable? A variable is an area into memory to store data.
Which data? For example, the color of a car, the best score of a player ... and so on.

Variables in programming are indispensable. We can do nothing without variables. So, imagine a program that will ask how old an user is. You may wish to print a message if the user is major or minor.

How to do that without variables :-)? It's simply impossible.

A variable in Gambas owns a datatype. For example, for the age of this user, the value is an interger so, the datatype of this variable will be an interger type. We have in Gambas several datatype, like:

A variable name must follow some rules:

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. That's a good way to well develop :-) . This will avoid you making some mistakes.

This is one way to declare a variable:

DIM variable AS Integer

You can assign a value like this:

DIM var1 AS Interger = 5
DIM myNickname AS String

myNickname = "GarulfoUnix" 'This is another way to assign a value

Right now, let's have a look at how to print this variable by using the PRINT statement:

' Gambas module file

PUBLIC SUB Main()

  DIM nickname AS String = "GarulfoUnix"

  PRINT "My nickname on internet is " & nickname

END

To concatenate any variables to any strings, 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 INPUT statement. Here is an example:

' Gambas module file

PUBLIC SUB Main()

  DIM nickname AS String

  PRINT "What is your nickname ?"
  INPUT nickname

  PRINT "Your nickname is " & nickname

END

When the program arrives at this line:

INPUT nickname

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