functions
Introduction
Functions allows to cut a program in several parts. That avoids to have a big Main() procedure. _
In
Gambas, you have got two types of "functions":
- Functions : return a value
- Procedures : Don't return any values.
Procedures
First of all, you have already saw 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 to pass parameters to the procedure. If you don't need to pass any arguments, then you can let empty brackets. This is an example to show how to use a procedure in a program :
functions
Sub sayHello()
Print "Hello !"
End
Public Sub Main()
sayHello()
End
The result is :
Hello !
This is another example but with arguments this time :
functions
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 that variable names of arguments. As you can see, Gambas has no problem with that :-) . But it's important to say that aren't the same variables !
|
Functions
Functions acts like procedures except they're returning a value. Their use and define are the same that procedures. We must just indicate which value type will be returned. For example, we're going to ask a number from user, and we'll show the square of this number :
functions
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 to define the accessibility of your procedure. I.e, if you have several
Gambas modules, that allows you to call these procedures in others modules.
However, if you want procedures and functions are only called in the same module, you must indicate the
PRIVATE keyword in front of your procedures and functions.