Android Question Returning several values from Sub from a Code Module

kepler

Active Member
Licensed User
Good morning,

I'm facing a pretty much doubt regarding functions in B4A.
If we want a Sub - in a module - to return 2 values in the Main, for instance, can we make the following routine:

Sub Function1 (sinput as double, sout1 as double, sout2 as double)
sout1 = 2 * sinput
sout2 = 3 * sinput
End Sub

?

It doesn't seem to work. Must we use Module1.sout1 and Module1.sout2 to retrive the values? But then, why should we pass them to the Sub?

Kind regards,

Kepler
 

eurojam

Well-Known Member
Licensed User
I use process_globals variables in the code module oder service modul. then you can use Module1.sout1...
B4X:
Sub Process_Globals
  Dim sout1, sout2 As Double
     
End Sub

Sub Function1 (sinput As Double)
  sout1 = 2 * sinput
  sout2 = 3 * sinput
End Sub
 

stevel05

Expert
Licensed User
If you don't want to use Global variables you can return an Array, a List, a Map or a Type structure that contain as many values as you like.
 

Troberg

Well-Known Member
Licensed User
This is pretty much standard in all languages, you only return one value.

However, that one value can be an object, which, in turn, can contain many values.

For example, say that you want to return coordinates for something. Instead of returning X, Y and Z, you define a class which has X, Y and Z as properties, and returns an object of that class. If you don't want any logic in the class, a type works as well.
 

kepler

Active Member
Licensed User
Hi,

Yes, those were the solutions I was using. I thought there was another way. Just checking ;)

Thanks anyway,

Kepler
 

RandomCoder

Well-Known Member
Licensed User
Good morning,

I'm facing a pretty much doubt regarding functions in B4A.
If we want a Sub - in a module - to return 2 values in the Main, for instance, can we make the following routine:

Sub Function1 (sinput as double, sout1 as double, sout2 as double)
sout1 = 2 * sinput
sout2 = 3 * sinput
End Sub

?

It doesn't seem to work. Must we use Module1.sout1 and Module1.sout2 to retrive the values? But then, why should we pass them to the Sub?

Kind regards,

Kepler
The normal way to return a value from a Function if not using a Global variable is the way that @DonManfred has demonstrated above. That is to declare the name of the Function followed by any input parameters contained within parenthesise and after that declare the return date type. In the function you then use the Return keyword to pass a value back to the calling sub.
 
Top