Adventure Game Studio

AGS Support => Advanced Technical Forum => Topic started by: eri0o on Sat 27/02/2021 14:07:36

Title: returning dynamic array of managed struct from a function [SOLVED]
Post by: eri0o on Sat 27/02/2021 14:07:36
So I have been doing a bit of a little pattern in my code:

Code (ags) Select
  t = new JsonToken[MAX_TOKENS];
  for(int i=0; i<MAX_TOKENS; i++) t[i] = new JsonToken;


So I decided to make a little function for it:

Header
Code (ags) Select
import JsonToken[] JsonTokenNewArray(int count); // this is line 33

Script
Code (ags) Select
JsonToken[] JsonTokenNewArray(int count)
{
  JsonToken tks[];
  tks = new JsonToken[count];
  for(int i=0; i<count; i++) tks[i] = new JsonToken;
  return tks;
}


Unfortunately this gives me an error "Error (line 33): cannot pass non-pointer struct array". I also tried to make this function be part of the JsonToken managed struct.

Header
Code (ags) Select
managed struct JsonToken {
  // ... a bunch of things ...
  import static JsonToken[] NewArray(int count); // $AUTOCOMPLETESTATICONLY$ // this is line 30
};


Script
Code (ags) Select
static JsonToken[] JsonToken::NewArray(int count)
{
  JsonToken tks[];
  tks = new JsonToken[count];
  for(int i=0; i<count; i++) tks[i] = new JsonToken;
  return tks;
}


But this gives me the error "Error (line 30): Member variable cannot be struct".

I am starting to think it's not possible to return a dynamic array of managed structs from a function, is this the actual error? (it's for a little Json parser module that is kinda working but I am just polishing the API right now..)
Title: Re: returning dynamic array of managed struct from a function
Post by: Crimson Wizard on Sat 27/02/2021 14:39:18
There are nuances of ags script syntax + bad parsing at times which causes confusing error messages.

In regards to your script, you are not declaring a proper type there, for example if you put this elsewhere alone -

Code (ags) Select

JsonToken tks[];


this will report you "Cannot declare local instance of managed type", because you are trying to declare an array of instances rather than pointers.

You have to add * to signify that it's array of pointers.

Code (ags) Select

import JsonToken*[] JsonTokenNewArray(int count)


Code (ags) Select

managed struct JsonToken {
  import static JsonToken*[] NewArray(int count);
};


Code (ags) Select

static JsonToken*[] JsonToken::NewArray(int count)
{
  JsonToken* tks[];
  tks = new JsonToken[count];
  for(int i=0; i<count; i++) tks[i] = new JsonToken;
  return tks;
}
Title: Re: returning dynamic array of managed struct from a function
Post by: eri0o on Sat 27/02/2021 14:45:36
OMG! Thank you! It worked! I knew it should be possible and it was a mistake in my code somewhere!  :-D Thank you!