Return multiple variables/values from function

Started by TMuh, Wed 06/11/2013 11:20:37

Previous topic - Next topic

TMuh

Hi,

Id like to return multiple values from function by using dynamic array. I have this simple function:
Code: AGS
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)

RickJ

The keyword "function" specifies that an int will be returned and you are attempting to return an int array.

Khris

In case it isn't clear, you need:
Code: ags
int[] GetLocation (int sx, int sy, int tdir, int tdis) {
  ...
  return r_xy;
}

TMuh


monkey0506

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
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
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

SMF spam blocked by CleanTalk