[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-users] 2D array question



On Mon, Mar 4, 2019 at 8:47 AM <amindfv@xxxxxxxxx> wrote:
> Yes, exactly. Basically scalar values are passed by value, objects (incl. arrays) are passed by reference.

I don't think that's the right explanation.

The issue is mutability. [0] is mutable. 0 is not.

That is, if you have a reference to some object A, there is a
difference between 1/ changing the reference so that it points to a
different object B or 2/ keeping the reference exactly the same, but
modifying the state of object A.

// array of 5 references to the integer 0
a = Array.fill(5, 0);
-> [ 0, 0, 0, 0, 0 ]

// now replace the second with a reference to integer 1
// only the specific reference changes
a[1] = 1;
-> [ 0, 1, 0, 0, 0 ]

// array of 5 references to an IDENTICAL array
a = Array.fill(5, [0]);
-> [ [ 0 ], [ 0 ], [ 0 ], [ 0 ], [ 0 ] ]

// now replace the second with a reference to a different array
// only the specific reference changes
a[1] = [1];
-> [ [ 0 ], [ 1 ], [ 0 ], [ 0 ], [ 0 ] ]

// now modify the state of the first subarray
// this subarray still has 3 other references!
a[0][0] = 2;
a
-> [ [ 2 ], [ 1 ], [ 2 ], [ 2 ], [ 2 ] ]

// array of references to 5 different array objects
a = Array.fill(5, { [0] });

// now modify the state of the first subarray
// this subarray has only one reference so the others don't change
a[0][0] = 2;
a
-> [ [ 2 ], [ 0 ], [ 0 ], [ 0 ], [ 0 ] ]

hjh

_______________________________________________
sc-users mailing list

info (subscription, etc.): http://www.birmingham.ac.uk/facilities/ea-studios/research/supercollider/mailinglist.aspx
archive: https://listarc.bham.ac.uk/marchives/sc-users/
search: https://listarc.bham.ac.uk/lists/sc-users/search/