Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: TMuh on Wed 06/11/2013 11:20:37

Title: Return multiple variables/values from function
Post by: TMuh on Wed 06/11/2013 11:20:37
Hi,

Id like to return multiple values from function by using dynamic array (http://www.adventuregamestudio.co.uk/forums/index.php?topic=40449.msg534028#msg534028). I have this simple function:
Code (AGS) Select
function GetLocation (int sx, int sy,  int tdir, int tdis) {
int r_xy[] = new int[2]; //(instruction i linked above suggested "int r_xy[] = new array[2];" here but it reported error for me)
int tdir2;
if (tdir == 90) {r_xy[0] = 0; r_xy[1] = sy-tdis; return r_xy;}
}


But Im getting this error: Math.asc(85): Error (line 85): Type mismatch: cannot convert 'int[]' to 'int'
So what Im doing wrong?
And is there any other ways to return multiple values? (except global variables)
Title: Re: Return multiple variables/values from function
Post by: RickJ on Wed 06/11/2013 14:01:24
The keyword "function" specifies that an int will be returned and you are attempting to return an int array.
Title: Re: Return multiple variables/values from function
Post by: Khris on Wed 06/11/2013 14:07:29
In case it isn't clear, you need:
Code (ags) Select
int[] GetLocation (int sx, int sy, int tdir, int tdis) {
  ...
  return r_xy;
}
Title: Re: Return multiple variables/values from function
Post by: TMuh on Wed 06/11/2013 16:31:19
ah, ok

thank you.
Title: Re: Return multiple variables/values from function
Post by: monkey0506 on Wed 06/11/2013 21:00:38
Quote from: TMuh on Wed 06/11/2013 11:20:37(instruction i linked above suggested "int r_xy[] = new array[2];" here but it reported error for me)

Sorry, that was a typo on my part. I often type these code snippets directly in the browser (and even sometimes from my phone), and make revisions as I go. I corrected that post for posterity's sake.

I will also point out that arrays are always passed by-reference, so if you needed multiple different types then you could do something such as:

Code (ags) Select
bool MultiVar(int myInts[], char myChars[], String myStrings[])
{
  myInts[0] = 5;
  myInts[1] = 42;
  myInts[2] = 99;
  myChars[0] = 'a';
  myChars[1] = 'n';
  myChars[2] = 'z';
  myStrings[0] = "lol";
  myStrings[1] = "ref";
  myStrings[2] = "goosnargh";
  return true;
}


Granted, this is a quite terrible example, but you could call it like:

Code (ags) Select
int theInts[] = new int[3];
char theChars[] = new char[3];
String theStrings[] = new String[3];
MultiVar(theInts, theChars, theStrings);
Display("%d", theInts[1]); // displays 42