Godot 4 Dictionary How to subtract a value from a key?

v4.5.stable.official [876b29033]

How to subtract a value from a key? I make a simple inventory

InventoryGlobal

var items: Dictionary = {}


func update_item(key, value):
	if items.has(key):
		items[key] += value
	else:
		items[key] = value
	
	if items[key] <= 0:
		items.erase(value)

InventoryUI

func _process(delta: float) -> void:
	for items in InventoryGlobal.items:
		if InventoryGlobal.items.has("Health Bottle"):
			heal_sprite.visible = true
	if InventoryGlobal.items.has("Health Bottle") == false:
		heal_sprite.visible = false
		heal_name.visible = false


func _on_health_button_pressed() -> void:
	if InventoryGlobal.items.has("Health Bottle"):
		HealthPlayer.MAX_HEALTH += 25
#I need a function that deletes one value from a key

This is a simple inventory for 3-4 items.

Seems like you can use your update_item funciton with negative numbers to subtract.

func _on_health_button_pressed() -> void:
	if InventoryGlobal.items.has("Health Bottle"):
		HealthPlayer.MAX_HEALTH += 25
		InventoryGlobal.update_item("Health Bottle", -1)
1 Like

Oh my God, I didn’t notice that, thank you very much. I guess I should go get some rest.

Not related to your question however:

func update_item(key, value):
    ...
	if items[key] <= 0:
		items.erase(value)

This looks incorrect.
value is equal to the number of items you wish to add to the dictionary.
On this last line you test if the number of items you have at key is less than or equal to zero.
If so, you then erase the item[value] where value still equals the number of items you want to add.
I think you want this to be items.erase(key)

2 Likes

Thank you, but I have already fixed this error. You don’t know how to output the value of a key using a label. You know, like in horror games.