Essentially, if you define a Global Variable (varA) and then define a second variable (varB) as {varB = varA}, changes to varB can sometimes alter varA.
Description
Details
- Severity
- Minor
- Resolution
- Open
- Reproducibility
- Always
- Operating System
- Windows 7
- Category
- Scripting
The following code results in test_var1 having "5" appended into it, despite that never being done.
test_var1 = [1,2,3,4]; test_var2 = []; test_var3 = [5]; test_var2 = test_var1; test_var2 pushBack (test_var3 select 0); hint str test_var1; //Should return [1,2,3,4], instead returns [1,2,3,4,5]
This method, however, appears to work properly.
test_var1 = [1,2,3,4]; test_var2 = []; test_var3 = [5]; {test_var2 pushBack _x} forEach test_var1; test_var2 pushBack (test_var3 select 0); hint str test_var1; //Properly returns [1,2,3,4]
Event Timeline
Does this happen with other data types as well or just arrays?
For arrays:
Your first example makes test_var2 point to the same array as test_var1, but if you deep copy it creates a new array with the same contents.
test_var2 = +test_var1;
https://community.bistudio.com/wiki/Array#Copying
https://forums.bistudio.com/forums/topic/193271-solved-how-to-get-pointers-and-copies-of-arrays/?do=findComment&comment=3074607
Arrays are referenced as pointers. If you do _array2 = _array1; both variables will contain reference to the same array. That's why if you change _array1 you will see change in _array2 and vice versa.
As _connor correctly suggested, you need to add the plus sign to force it to create a copy of the array. It will look like this: _array2 = +_array1; This way you can independently modify both arrays.