Multiple Returns?

BlitzMax Forums/BlitzMax Programming/Multiple Returns?

Tibit(Posted 2005) [#1]
Can a function or method return more than one value somehow?

X,Y = GetLocation()


Robert(Posted 2005) [#2]
You can either use Var parameters:

Local x,y

getLocation(x,y)

Print x
Print y

Function getLocation(x var, y var)
   x=3
   y=4

   Return True
End Function


Or use a custom type:

Type Position
  Field _x
  Field _y
End Type

Local pos:Position=getLocation()

Print pos._x
Print pos._y

Function getLocation:Position()
   Local pos=New Position
   pos._x=3
   pos._y=4

   Return pos
End Function



Beaker(Posted 2005) [#3]
Or use an array:
Strict

Local b:Int[] = getLocation()

For Local t:Int=EachIn b
        Print t
Next


Function getLocation:Int[]()
	Return [3,4]
End Function


Although for what you want I recommend Roberts first example.


FlameDuck(Posted 2005) [#4]
I recommend his second. Chances are you're going to want to have some sort of 2DVector class anyhow...


Tibit(Posted 2005) [#5]
Thanks!

I have been returning Types, Lists and Arrays. The Var command was what I was looking for. In some cases that is more clean.

@ Beaker, did you know you can do it like this directly?
For Local Thing = EachIn LocationA()
    Print Thing
Next

Function LocationA:Int[]()
     Return [3,4,5,6,7,8]
End Function


Where can I find the var command in the reference?


Steve Elliott(Posted 2005) [#6]
Thanks for that Robert I didn't know you could use var to return more than one value.


Robert(Posted 2005) [#7]
Where can I find the var command in the reference?


The docs are not that well organised unfortunately, but the easiest way is to open a new source file, type in 'Var' and press F1 a couple of times.


FlameDuck(Posted 2005) [#8]
Thanks for that Robert I didn't know you could use var to return more than one value.
Distinction: VAR does not allow you to return more than one value. Rather, var allows you to return no values at all, but be able to directly manipulate the variables passed.

This is known as passing by reference (as opposed to passing by value, which protects the original data from corruption).


Steve Elliott(Posted 2005) [#9]
I suppose so - return isn't used in the traditional manner - return(result). But it's a neat way of coding something I need to do right now.


RexRhino(Posted 2005) [#10]
I don't know how it works in BlitzMax, but in C passing by reference was/is considered the fastest way to "pass" variables.

Nowadays, I am not so sure that is the case, and with modern machines it doesn't really matter in most cases. But I suppose if speed is what you are after, you should pass by reference.