GameMaker Arrays and Memory

T

Taylor Romey

Guest
Hello all,

I have some questions about arrays and memory usage. I have a background in C and am wondering the following:
  • Is it possible to initialize an array of a set size and not assign any values to any positions and therefore have them as null values? ie. myarray[size]; where size is an integer. In C it would be like "int myarray[20];"
  • If I assign a value to say index "myarray[20] = x;", would all the other slots before index 20 remain unassigned?
  • Given that, would assigning a value only to index 20 only open memory space for the size of one value, or would it open 20?
Thank you
 

CMAllen

Member
Yes. If you declare an array from its largest dimension, GM will allocate the array for that entire size. The other indices will be assigned but empty. For 1d arrays. The second dimension of a 2d array is of arbitrary length. If you declare a 2d array[20,20] GM will allocate the space for the first dimension worth of 20 addresses, and an additional 19 addresses for the 2nd dimension for that one section of the array.
 

Hyomoto

Member
That would make an array of nested arrays at best, an array with the same nested array in every indice at worst.

For 2d arrays, GM2 is still a little behind. We got some incredible new functionality with array_create and nesting arrays, but there is no easy way to build 2d arrays without coding it yourself. To answer those questions, all indices have to have something and I believe by default it is 0. All arrays in GM are ragged, so initializing a later value leaves all earlier ones set to that default which, again, I think is 0. And lastly the entire memory is allocated.
 

Simon Gust

Member
You can always make your own function
1D
Code:
/// array_create_custom_1d(size, value)
var size = argument0;
var value = argument1;
var array;
for (var i = size-1; i >= 0; --i)  {
    array[i] = value;
}
return (array);
and for 2D
Code:
/// array_create_custom_2d(sizeA, sizeB, value)
var sizeA = argument0;
var sizeB = argument1;
var value = argument2;
var array;
for (var i = sizeA-1; i >= 0; --i) {
for (var j = sizeB-1; j >= 0; --j) {
    array[i, j] = value;
}}
return (array);
you could still only use 1 for-loop like this
Code:
for (var i = sizeA-1; i >= 0; --i)  {
    array[i, sizeB-1] = value;
}
but it would again clear all indexes except the last one to 0 or depending on platform <undefined>.
How do you make scripts in GMS 2 again? Some mumbling at the start of the script that doesn't do very much?
 
Top