B4A - Ch1 - Section 4 - Procedures (Subs and Functions)

In traditional Basic we are use to procedures and members/methods that are known as both "Sub" and "Function". In B4A however, we only refer to them as, "Sub" for subroutine. The only difference is when you want to return something like a Function would, you will use the "return" keyword with some value just like you would in C, Java, PHP, etc..

Just before we used the terms: procedure, member and method. So what re these? In all actuality the terms, "procedure, function, subroutine, subprogram, method, and member" are all basically the same thing. If we were using this in the OOP terminology (object orientated programming), like a class then we would be referring to the subroutine as a "member" or "method". However if you are not using it in the OPP sense then it is safe to call the subroutine a "procedure". Don't really worry about it just yet we'll explain this a little better later on.

Subroutines (Sub) can sending parameters but they do not return any value. This is the equivalent to VOID keyword in C, Java and other languages.

In Basic, Functions return data according to their data type specified.

Sample Subroutines

Sleep is a great example because we are going to be using a few different keywords such as DateTime, Do Until and DoEvents.

Sub Sleep(ms As Long)
  Dim now As Long
  If ms > 1000 Then ms =1000 'avoid application not responding error
  now=DateTime.Now
  Do Until (DateTime.Now>now+ms)
     DoEvents
  Loop
End Sub

 

Sample Functions

Sub AddIntegers (i1 as Int, i2 as Int)
  Return (i1 + i2)
End Sub