arraysappendgodotgodot4

Godot 4 Array append changes all existing records as well


I was able to solve this but I dont understand how.

When I perform an append to an array, the last value appended becomes the value for all the records in the array.

var myBus=BusinessType.new()

func _on_load
   for i in businesses_json.get_data():
    
    myBus.name=i.name
    print ("showint previous array after name:")
    for j in Global.businesses:
        print (j.name)
    myBus.location=i.location
    print ("adding "+myBus.name)    
    Global.businesses.append(myBus)
    print ("now the global array is:")
    for j in Global.businesses:
        print (j.name)

and this provides the output below.

showint previous array after name:
adding first
now the global array is:
first
showint previous array after name:
second
adding second
now the global array is:
second
second
showint previous array after name:
third
third
adding third
now the global array is:
third
third
third
number business = 3

When I move the

var myBus=BusinessType.new()

to within the for i loop then I get the correct output

showint previous array after name:
adding first
now the global array is:
first
showint previous array after name:
first
adding second
now the global array is:
first
second
showint previous array after name:
first
second
adding third
now the global array is:
first
second
third
number business = 3

Can someone explain why re-defining the variable at each loop solved the problem ? is it acting as a pointer somehow ? Does this not consume more memory resources have to re-define at each iteration ?

Is there a better way ?


Solution

  • The variable myBus is defined outsid the loop and is used throughout all iterations. This means that you are appending the same object (myBus) to the Global.businesses array multiple times. Consequently, each element in Global.businesses ends up being a reference to the same object. Since myBus is the same object, any changes made to myBus are reflected in all entries in Global.businesses. By the time the loop completes, all entries in Global.businesses point to the last state of myBus, hence why all records have the same value. I try to instantiate new objects inside loops or functions whn I need separate instances. Yes, you will require more memory for a new object in each iteraion, but its probably going to be negligible.