[SOLVED] Loop not creating array or list of arrays as expected

I'm trying to use a for loop to create an array of arrays and I have no clue why it doesn't work. The same problem is encountered if I try to use a DS list of arrays. A reproduction of my code is:

GML:
var k = 4;

var array;
var list = ds_list_create();

for (var i=0; i<k; ++i) {
    var t;
    t[1] = i + 1;
    t[0] = i;
    
    array[i] = t;
    ds_list_add(list, t);
 
    show_debug_message(string(array));
     
    for (var l=0; l<ds_list_size(list); ++l) {
        show_debug_message("list " + string(ds_list_find_value(list, i)));
    }
}
The debug messages show that, at each iteration, the value at each index of array and list is being overwritten by the current value of t.

This means the array returns as [ [ 3,4 ],[ 3,4 ],[ 3,4 ],[ 3,4 ] ], as does the DS list, instead of the [ [ 0,1 ],[ 1,2 ],[ 2,3 ],[ 3,4 ] ] I would expect.

If I instead store i in the array and list as so:

GML:
array[i] = i;
ds_list_add(list, i);
both the list the array and the list return as [ 0,1,2,3 ] as expected. This leads me to believe there is something I'm missing with how arrays are treated in GML2. Can anyone help me understand why this is happening?
 
Last edited:

chamaeleon

Member
Try initialization t to an empty array? I suspect not giving an initializer means it will keep the reference to the array it already has as it loops. Initializing it forces it to start with a new empty array each iteration.
GML:
var t = [];
 
Try initialization t to an empty array? I suspect not giving an initializer means it will keep the reference to the array it already has as it loops. Initializing it forces it to start with a new empty array each iteration.
GML:
var t = [];
Thanks, that worked perfectly!
 
Top