Hi,
I'm using the following code to transfer data between 2 dictionaries.

func _on_hire_pressed():

if PlayerWealth.totalcost <= PlayerWealth.coin: 
	for i in range(0, 5):  
		var checkbox = get_node("VBoxContainer/Raster/RecruitList/CheckBox" + str(i))
		if checkbox.is_pressed():  
			var heroData = HeroesData.generated_heroes[int(i)]  # Accessing the corresponding hero data
			HeroesData.heroes.append(heroData)  # Transferring data to heroes dictionary
			HeroesData.generated_heroes.erase(heroData)

	PlayerWealth.coin -= PlayerWealth.totalcost
	PlayerWealth.totalcost = 0
	buynow.emit()
	self.queue_free()
else:
	warning.text = "[center]insufficient funds![/center]"

I think the problem i'm having is that by erasing the data i'm changing the index value of the remaining data.
could anyone tell me a way to fix this?

  • Okay. In this case forget about erase. That will indeed break the indexing. Simplest solution would be to assign null to

    generated_heroes[i]

    But you should also check if heroData is null.

The dictionary erase function expects the key. You are passing the value. Replacing the heroData argument with i should do it.

Edit: Dictionary does not have an append function. So I assume that heroes is actually an array and not an dictionary.

    Zini
    Thank you for answering,
    I changed the code but now it doesn't remove any data. Any idea what went wrong?

    if PlayerWealth.totalcost <= PlayerWealth.coin: 
    	for i in range(0, 5):  
    		var checkbox = get_node("VBoxContainer/Raster/RecruitList/CheckBox" + str(i))
    		if checkbox.is_pressed():  # Checking if the checkbox is checked
    			var heroData = HeroesData.generated_heroes[int(i)]  # Accessing the corresponding hero data
    			HeroesData.heroes.append(heroData)  # Transferring data to heroes dictionary
    			print(HeroesData.generated_heroes.size())
    			HeroesData.generated_heroes.erase(i)
    			print(HeroesData.generated_heroes.size())

    Are you actually using dictionaries at all? Because if both containers are arrays this code would be completely wrong.

      Zini
      It appears you are correct in that I'm actually using arrays. I'm sorry, I'm quite new to this.

      Okay. In this case forget about erase. That will indeed break the indexing. Simplest solution would be to assign null to

      generated_heroes[i]

      But you should also check if heroData is null.