• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Copying struct by value to new array index

ophelius

Member
I have an array of structs. I want to make a copy and place it at the end of the array, but anything I do, the new copy is a reference to the old one, so any changes I make will change the old struct also.
This is what I've tried:
Code:
var NewStruct = {};
NewStruct = Array[Index];
array_insert(Array, array_length(Array), NewStruct);
At this point the new struct is added and is identical to the struct at Array[Index], but like I mentioned, it's only a reference.
I've tried using array_resize with array_copy() as well, same thing.
How can I make a new copy so I can modify the new one without modifying the original?
Thanks
 
Structs are always passed by reference, so you need to explicitly and "manually" copy/clone it one way or other.
If the struct's structure (list of contained variable names) doesn't change and is predictable, you could write a static Copy() method for it that returns a new struct with the same values:
GML:
function Vector2 (_x, _y) constructor {
    x = _x;
    y = _y;
    static Copy = function() {
        return new Vector2(x, y);
    }
}

// And then when you use it in an array:
var NewStruct;
NewStruct = Array[Index].Copy();
array_insert(Array, array_length(Array), NewStruct);
Otherwise, you can make copies of any kind of struct by utilizing these built-in functions:
  • variable_struct_get
  • variable_struct_set
  • variable_struct_remove
  • variable_struct_get_names
  • variable_struct_names_count
 

ophelius

Member
Thank you. Unfortunately this array of structs is created from a json_parse, so I'm not explicitly declaring them so I can't make a copy function like that. Unless there is a way? Not sure.
I was looking at the manual about arrays passed to functions and it talks about the function making a copy if an element is modified. I can't quite put my head around that, but maybe the array can be passed thru a function just to make a copy, then the function would add it to the end of original array somehow? Not sure if that would work.
 
Last edited:

DaveInDev

Member
funny, I just asked something very similar a few hours ago.


and @Greenblizzard pointed out a library with a function that could interest you :

 

ophelius

Member
funny, I just asked something very similar a few hours ago.


and @Greenblizzard pointed out a library with a function that could interest you :

Hey thanks, looks very useful and exactly what I need, I'll report back later if it works
 
Top