Dictionary is empty, But the line of code still runs.

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

I watched the entire tutorial series by arkeve on how to make an inventory system. I noticed that in the videos, There was nothing on how to actually use items in the hotbar. I tried making my own script which is written like this:

if Input.is_action_just_pressed("Click"):
   if PlayerInventory.hotbar != {}:
      print(PlayerInventory.hotbar)

PlayerInventory is a singleton btw.
When I run this line and click, It should print the hotbar because there is atleast on item in the hotbar dictionary. When I remove everything from the hotbar dictionary, It should print the hotbar because it is empty. It still prints it. Why is it doing this?
tl;dr The hotbar is equal to {} so it shouldn’t run the line but it still runs.

:bust_in_silhouette: Reply From: Abl3t0nnile

You could simply :

if PlayerInventory.hotbar:
    print(PlayerInventory.hotbar)

If/Else checks against a dict or list always return false if the datastructure ist empty.

:bust_in_silhouette: Reply From: DaddyMonster

Godot has the built in method empty() to the rescue - it returns true if the dict is empty. So just:

if Input.is_action_just_pressed("Click"):
   if not PlayerInventory.hotbar.empty():
      print(PlayerInventory.hotbar)

TYSM!!! I had been trying to figure this out for weeks

Mr. Gamezz | 2022-01-09 21:50