Page MenuHomeFeedback Tracker

Modifying a Global Variable can impact other Global Variables
Closed, ResolvedPublic

Description

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.

Details

Severity
Minor
Resolution
Open
Reproducibility
Always
Operating System
Windows 7
Category
Scripting
Steps To Reproduce

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

Gnashes created this task.Sep 24 2017, 8:59 PM
Gnashes edited Steps To Reproduce. (Show Details)
Gnashes edited Steps To Reproduce. (Show Details)

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.

Wulf closed this task as Resolved.Oct 4 2017, 11:07 AM
Wulf claimed this task.