returning dynamic array of managed struct from a function [SOLVED]

Started by eri0o, Sat 27/02/2021 14:07:36

Previous topic - Next topic

eri0o

So I have been doing a bit of a little pattern in my code:

Code: ags
  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
import JsonToken[] JsonTokenNewArray(int count); // this is line 33


Script
Code: ags
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
managed struct JsonToken {
  // ... a bunch of things ...
  import static JsonToken[] NewArray(int count); // $AUTOCOMPLETESTATICONLY$ // this is line 30
};


Script
Code: ags
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..)

Crimson Wizard

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

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

import JsonToken*[] JsonTokenNewArray(int count)


Code: ags

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


Code: ags

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

eri0o

OMG! Thank you! It worked! I knew it should be possible and it was a mistake in my code somewhere!  :-D Thank you!

SMF spam blocked by CleanTalk