Test control and loop structures
Without these structures, our programs would work in a sequential way, and would be very poor.
Test structures
This allows us to perform some instructions if a condition is true.
If ... Then
This is the structure the most basic:
condition is the expression to test. The condition signs are:
-
>
: purely upper
-
<
: purely lower
-
>=
: upper or equal
-
<=
: lower or equal
-
=
: equal
-
<>
: unlike
Thus we can compare two values, two variables for example:
If Variable1 = Variable2 Then
Here, the "=" sign indicates an equality test, and not a value being assigned to a variable (like in a = 1).
Now, Here is an example to show that:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
The
ELSE keyword is optional. Example:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
Another note, the
ENDIF keyword is optional if there is only one instruction to execute:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
The Select ... Case structure
We're using this structure when there are many values to test. With this structure, our code is more clear to read:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
Loops
Loops allows you to repeat one or more instructions. Three loops type exists allowing you to do the same thing in a different way.
For
The For loop allows to repeat an instructions block
n times.
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
When Gambas enters the loop for the first time, it applies the value 1 to
i, then executes next instructions until it meets the
NEXT keyword. Gambas returns to the beginning of loop, then increments the
i variable until it reaches 5. The loop instructions will be read 5 times:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Do ... Loop
Sometimes we don't know the number of loops to do. But we know how it must stop. Here is an example:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
We can also use the
WHILE keyword instead of
UNTIL to make a loop structure with a condition.
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
While
About
WHILE, there is a loop structure specially for While:
[gb.markdown].Markup.ProcessCode.1104: Cannot load component 'gb.highlight': cannot find component
Value of age : 1
Value of age : 2
Value of age : 3
Value of age : 4
Value of age : 5
Value of age : 6
Value of age : 7
Value of age : 8
Value of age : 9
Value of age : 10
You can go to the next tutorial, we have finished with loops.