function changes arrays which it shouldnt

I was trying to create a function to edit an array, and came across this annoying problem.
If you have a function which gets given an array as an input, and inside the function you set two other arrays to be that input, and then change one array in a loop, all three arrays will be changed. Below is an example of this, executed in the maxscript listener.

fn testFunction input =
(
 tempArray1 = input
 tempArray2 = input
  --this is here to stop "!REG3XP1!>" appearing(it gets added to the post unless I have something here) and messing up the rest of the code
 for i = 1 to input.count do
 (
  tempArray2[i] = 0
 )
 return #(tempArray1, tempArray2)
)
testFunction()
 
testArray = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
#(1, 2, 3, 4, 5, 6, 7, 8, 9)
 
newTestArray = testFunction testArray
#(#(0, 0, 0, 0, 0, 0, 0, 0, 0), #(0, 0, 0, 0, 0, 0, 0, 0, 0))
 
newTestArray[1]
#(0, 0, 0, 0, 0, 0, 0, 0, 0)
 
newTestArray[2]
#(0, 0, 0, 0, 0, 0, 0, 0, 0)

testArray
#(0, 0, 0, 0, 0, 0, 0, 0, 0)

As you can see, it changes all three of the arrays to have nothing but 0, which it shouldn't.
I can see no reason for this behaviour, but it's quite probable I have missed something which is causing it to work like this, if not does anyone know why this happens and any way to avoid it?

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
miauu's picture

.

If my english is better I can explain why the arrays behaves like this, but... :)
Think that when you use:

tempArray1 = input
 tempArray2 = input

the tempArray1 and tempArray2 are a pointers to the input array. So, changing the value in one of the three arrays will change the values in all arrays.

The solution is to use deepCopy when you create the other two arrays.

brttd's picture

Oooh, ok. That makes sense,

Oooh, ok.
That makes sense, thanks for the answer :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.