Topic was automatically imported from the old Question2Answer platform.
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?
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.
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: