Pre-filling array

What is the difference between this, which does not seem to work

`
const Ntrend = 169;
local test = array(Ntrend,[0,0]);

`

and this, which does work

`
const Ntrend = 169;
local test = array(Ntrend,[0,0]);

for(local a=0;a<Ntrend;a+=1){
test[a] = [0,0];//it seems to be necessary to pre-fill the array
}
`

I test it with this code and what I found is the entire array is filled with the last element I write to it unless I loop through and fill the array with [0,0] first. I don’t see the difference but the result is different.

for(local a=0;a<Ntrend;a+=1){ local b = 1.2 * a; test[a][1] = b;// } server.log("TEST") ; server.log(http.jsonencode(test));

wrong output is this, 201.6 is the last value written
[ [ 0, 201.6 ], [ 0, 201.6 ], [ 0, 201.6 ], [ 0, 201.6 ]… and so on

correct output is
[ [ 0, 0 ], [ 0, 1.2 ], [ 0, 2.4 ], [ 0, 3.6 ], [ 0, 4.8 ], [ … and so on

I’m kinda guessing here, but I suspect that this:

local test = array(Ntrend,[0,0]);

Puts a reference to the same object in each array element, so that when you write via the array, every write goes to the same object.

Whereas this:

for(local a=0;a<Ntrend;a+=1){ test[a] = [0,0];//it seems to be necessary to pre-fill the array }

Puts a different object in each array element.

Yep:

`
local N = 4;
local X = [0, 0];
local arr = array(N, X);

arr[2][0] = 123;
arr[2][1] = 312;

server.log("" + X[0] + ", " + X[1]);
`

This is documented here:

each of the new array’s new items will be populated with a copy of the value — or a single reference to it if the value is another array, a blob, a function, an object or a table.

(emphasis mine)

got it, thanks!

I’ll just leave the code that works and make sure it’s well commented.