iChunkiMunki
Member
Hey guys, often when you are making a complex game we use arrays like objects holding many
different variable types and even arrays. Sometimes we have arrays nested in arrays, nested
in another array, ..... nested in yet another array. Is there a limit to how deep the rabbit hole goes?
I often find that duplicating the parent array to be tedious because there are always pointers being copied (references to the original array) and when I change data in one array the changes carry over to all arrays.
With this script, it will recursively dig down into the deepest recesses of your nested arrays and copy all of the data -- not the pointers.
different variable types and even arrays. Sometimes we have arrays nested in arrays, nested
in another array, ..... nested in yet another array. Is there a limit to how deep the rabbit hole goes?
I often find that duplicating the parent array to be tedious because there are always pointers being copied (references to the original array) and when I change data in one array the changes carry over to all arrays.
With this script, it will recursively dig down into the deepest recesses of your nested arrays and copy all of the data -- not the pointers.
Code:
/// array_duplicate(arr);
/// @param array[]
/*
copy the contents of array
to new array using recursive
array handling -- making
all data NEW, no pointers
(Compatible with GMS1.4 and GMS2)
*/
var _source = argument0, /// source array
_size = array_length_1d(_source), /// size of source array
_dest = array_create(_size); /// destination array
///--------------- Copy all data element-wise with loop
for (var i=0; i<_size; i++){
/// if data in array is an array, duplicate that array as well
if(is_array(_source[i])){
/// recursively duplicate all nested arrays
var _temp = array_duplicate(_source[i]);
_dest[i] = _temp;
} else {
var _temp = _source[i];
_dest[i] = _temp;
}
};
return(_dest);