Using append() on an Array is behaving weirdly. Can someone help explain what I'm doing wrong?

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

I seem to be doing something wrong when I append an Entry into the Array.

I’m expecting an Array of Entry objects that I can then sort using a custom sort function.

extends Panel


var month: Month
var entries_array: Array = []


onready var ViewEntry = load("res://views/ViewEntry.tscn")
onready var vbox_entries: VBoxContainer = $ScrollContainer/VBoxEntries


func insert_entry(new_entry: Entry) -> void:

    print("New Entry")
    print(new_entry.to_string())

    print("Pre Append...")
    for entry in entries_array:
	    print(entry.to_string())

    entries_array.append(new_entry)

    print("Post Append...")
    for entry in entries_array:
	    print(entry.to_string())

Produces the following output:

New Entry
1 January 2020 Outgoing: £10 1/1/2020 10
Pre Append…
Post Append…
1 January 2020 Outgoing: £10 1/1/2020 10
New Entry
2 January 2020 Outgoing: £20 2/1/2020 20
Pre Append…
2 January 2020 Outgoing: £20 2/1/2020 20
Post Append…
2 January 2020 Outgoing: £20 2/1/2020 20
2 January 2020 Outgoing: £20 2/1/2020 20

The issue is likely with how you call Insert_entry (a part that you omitted) , how Entry is defined (a part that you omitted as well) or what your to_string-method returns (which again you omitted). Please provide all relevant code.

The code you provided looks fine and shouldn’t produce an issue.

njamster | 2020-08-04 13:04

I finally tracked down the issue myself.

It has nothing to do with storing the Entry objects into an Array and everything to do with how Entry is defined, as you point out.

I didn’t account for Objects being passed as references, so the passed Entry objects all refer (further back in the code) to the same initial Entry object… doh!

What is the etiquette for answering ones own asked question on this board?

rKinson | 2020-08-04 18:29