array append adds items into wrong array

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lowpolygon
extends Node2D

var testArr : Array
var testArr2 : Array


func _ready():
	testArr.append(Vector2(1,2))
	testArr2.append(4)
	
	print(testArr.size())
	print(testArr[0])
	print(testArr[1])

print result
2
(1, 2)
4

This is a test file , I created 2 arrays and adds one item only to each array.
But when I print the result from testArr, it will contains 2 items and it seems to include
item I appended to another array. What did I do wrong ? or is this a bug?

:bust_in_silhouette: Reply From: kidscancode

It seems that since you aren’t initializing the variables, the type hinting is assigning them both to the same array object. Doing this:

var testArr : Array = []
var testArr2 : Array = []

or this

var testArr : Array = Array()
var testArr2 : Array = Array()

Works as you would expect.

Thank you so much.But if I print out the second array , it would give me exactly the same print result. What I don’t understand is even uninitialized, it shouldn’t add items to arrays that I didn’t add to.

lowpolygon | 2019-04-16 07:32

:bust_in_silhouette: Reply From: wombatstampede

Those arrays haven’t been initialized. Therefore the content is undefined.
So either initialize your arrays before using them:
testArr = []; testArr2 = []
or initialize them right on declaration.

Anyway I’d still rate this as unexpected/unwanted behaviour.
… and there has already been filed a similar issue so it’ll hopefully be dealt with in 3.2:

(Edit: Oh… too slow… :wink:

Thanks for the help. That clears thing up

lowpolygon | 2019-04-16 07:35