Array (mis)behavior

I’m having some major frustration with an array. My array is composed of 1-12 other arrays. So far, so good. However, when I load the sub-arrays into to main array and later read it back, it’s behavior is a mystery. I will read the right number of sub arrays, but each is an identical copy of the last sub array. I confirmed that each appended sub array is unique as it is added to the main array.

Here’s the code snip:
transferArray is a local to this function
recordarray is a global which gets refreshed by a function called just prior to appending to transferArray.

									s = "record array# " + i + ": "
									for (local n=0; n < recordarray.len(); n++) s += recordarray[n] + " "
									server.log(s)            //shows the array being added
									transferArray.append(recordarray)

So each different recordarray gets added to the transferArray, confirmed to be unique. Yet when I check later in the code

						for (local x=0; x<transferArray.len(); x++)
						{
							for (local n=0; n<DATA_FIELDS; n++) 
								{
									s += "(" + x + ":" + n + ") " + transferArray[x][n] + " "
								}
						}
						server.log(s)   //shows actual contents of transferArray

I get multiple copies of my last entry, not the unique recordarrays that should have appended

Am I missing something obvious? I’d appreciate some suggestions.

I knew this would happen as soon as I posted the question.

Mulling over the situation while doing another chore, I realized that I needed to “clone” the sub array into the master array. That works. Wasted hours, but at least found the answer.

So now my code is
transferArray.append(clone(recordarray))

and it works.

So for others having this problem … bring in the clones!

1 Like

Yes, this is because you’re appending a reference each time, not the actual object. See the “duplicating objects” section of https://electricimp.com/docs/squirrel/squirrelcrib/

Sorry it took a while for you to figure this out - on the upside it won’t bite you again :slight_smile:

transferArray.append(clone(recordarray))

Note that clone only does a shallow copy, so if your array contains other references, they’ll be aliased, rather than cloned.

Personally, I’d consider resetting recordarray to a new array when you need a new one / after you’re done with it.