Jibble

Author Topic: returning dynamic array of managed struct from a function [SOLVED]  (Read 172 times)

eri0o

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

Code: Adventure Game Studio
  1.   t = new JsonToken[MAX_TOKENS];
  2.   for(int i=0; i<MAX_TOKENS; i++) t[i] = new JsonToken;

So I decided to make a little function for it:

Header
Code: Adventure Game Studio
  1. import JsonToken[] JsonTokenNewArray(int count); // this is line 33

Script
Code: Adventure Game Studio
  1. JsonToken[] JsonTokenNewArray(int count)
  2. {
  3.   JsonToken tks[];
  4.   tks = new JsonToken[count];
  5.   for(int i=0; i<count; i++) tks[i] = new JsonToken;
  6.   return tks;
  7. }

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: Adventure Game Studio
  1. managed struct JsonToken {
  2.   // ... a bunch of things ...
  3.   import static JsonToken[] NewArray(int count); // $AUTOCOMPLETESTATICONLY$ // this is line 30
  4. };

Script
Code: Adventure Game Studio
  1. static JsonToken[] JsonToken::NewArray(int count)
  2. {
  3.   JsonToken tks[];
  4.   tks = new JsonToken[count];
  5.   for(int i=0; i<count; i++) tks[i] = new JsonToken;
  6.   return tks;
  7. }

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..)
« Last Edit: 27 Feb 2021, 14:45 by eri0o »

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: Adventure Game Studio
  1. JsonToken tks[];
  2.  

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: Adventure Game Studio
  1. import JsonToken*[] JsonTokenNewArray(int count)
  2.  

Code: Adventure Game Studio
  1. managed struct JsonToken {
  2.   import static JsonToken*[] NewArray(int count);
  3. };
  4.  

Code: Adventure Game Studio
  1. static JsonToken*[] JsonToken::NewArray(int count)
  2. {
  3.   JsonToken* tks[];
  4.   tks = new JsonToken[count];
  5.   for(int i=0; i<count; i++) tks[i] = new JsonToken;
  6.   return tks;
  7. }
  8.  
« Last Edit: 27 Feb 2021, 14:41 by Crimson Wizard »

eri0o

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