Gambas/Subroutine

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Subroutine in Gambas is a piece of code maintained as a block usable in many parts of your program. You need not write it twice. Routines can return a value depending on their return type. For instance we can return a String or Integer. Let's check the example below:

 Public Sub Multiplying() As String
   Dim n, v1, v2 As Integer 
   Dim res As String
   n = 4 'multiplied by 9
   v1 = (n - 1) '3
   v2 = (10 - n) '6
   res = v1 & v2 'result 36
   Print res '4*9=36
   Return "9*" & n & "=" & res
 End

Later on we can use this subroutine in main program as:

 Public Sub Form_Open()
   Message.Info(Multiplying())
 End

We declare return type of subroutine after AS written in close relation to the name of subroutine as we can see in examples above. There are some built in subroutines connected with events of windowed program. Such a type is Form_Open() fired when form opened. Special name for subroutines used in classes based on the object oriented principle is methods. To say it simple: Subroutine is reusable part of code. Another example in our code might be:

 Public Sub sayHello()
   Message.Info("Hello Maria")    
 End

After creating of subroutine we can use it in similar way:

 Public Sub Form_Open()
  sayHello()
  Message.Info(Multiplying())
 End