functions
Introduction
Functions allows you to cut a program in several parts. That avoids you having a big Main() procedure.
In Gambas, there are two types of "functions":
-
Functions : return a value
-
Procedures : Don't return any values.
Procedures
First of all, you have already seen a procedure. Its name is
Main() :-). This procedure is a little special because it is the first procedure that the Gambas interperter starts to read. Here is how to define a procedure:
Sub procedureName(arguments)
End
Arguments allow you to pass parameters to the procedure. If you don't need to pass any arguments, then you can leave the brackets empty. This is an example to show how to use a procedure in a program:
Sub sayHello()
Print "Hello!"
End
Public Sub Main()
sayHello()
End
The result is:
Hello!
This is another example but with arguments this time:
Sub infoUser (firstname As String, age As Integer)
PRINT "Firstname : " & firstname
PRINT "Age : " & age
End
Public Sub Main()
Dim firstname As String
Dim age As Integer
Print "What is your name? "
Input firstname
Print "How old are you?"
Input age
infoUser(firstname, age)
End
The result is:
What is your name?
François
How old are you?
21
Firstname : François
Age : 21
Variable names can be the same as the variable names of the arguments. As you can see, Gambas has no problem with that :-). But it's important to say that they aren't the same variables!
Functions
Functions acts like procedures except they're returning a value. Their use and definition is the same as procedures. We must just indicate which value type will be returned. For example, we're going to ask a number from the user, and we'll show the square of this number:
Public Sub Main()
Dim nombre As Integer
Print "Please type a number: "
Input nombre
Print "The square of " & nombre & " is " & carre(nombre)
End
Function carre (nombre As Integer) As Integer
Return nombre * nombre 'indicate the value that the function returns.
End
To get the returned value of the function, you must declare a variable to store the result.
Accessibility
The Main() procedure is preceded by the
PUBLIC keyword. For this procedure, that's its signature. But for procedures that you're defining youself, this keyword allows you to define the accessibility of your procedure. i.e, if you have several Gambas modules, this allows you to call these procedures from other modules.
However, if you want procedures and functions that are only called in the same module, you must indicate the
PRIVATE keyword in front of your procedures and functions.