Correct way using Bit flags

Godot Version

4.2.1

Question

If having a system, which checks for several flags, are bit flags a suitable way?

Example:

@export_flags("TIRES", "WHEEL", "WINDSHIELD") var car: int = 0

func _ready():
	match car:
		1:
			print("TIRES chosen")
		2:
			print("WHEEL chosen")
		4:
			print("WINDSHIELD chosen")
		3:
			print("TIRES & WHEEL chosen")
		5:
			print("TIRES & WINDSHIELD chosen")
		6:
			print("WHEEL AND WINDSHIELD chosen")

Im using match for checking which flags has been chosen, but thats obviously not smart, since the possibilties grows exponentionally with every new flag.

Is there a better way of using bit flags?

In this case its better to export bool and write a function for each
new flag.

Check the flags individually instead:

const CONST_TIRES = 0x01 # Using hexadecimals, since that makes more sense when the bit set grows
if (car & CONST_TIRES):
   print("tires")
2 Likes

Since you mentioned exporting bools as an alternative, I’ll add that using bit flags is essentially no different from exporting a bunch of bools, it’s just more compact.

It also lets you define sets of flags which can be assigned/checked all at once, e.g.:

const CAR_CONVERTIBLE = 0b011 # only tires and wheels
1 Like
enum Components{
    TIRES = 1 << 0,
    WHEEL = 1 << 1,
    WINDSHIELD = 1 << 2,
}

@export_flags("TIRES", "WHEEL", "WINDSHIELD") var car: int = 0

func _ready():
	match car:
		Components.TIRES:
			print("TIRES chosen")
		Components.WHEEL:
			print("WHEEL chosen")
		Components.WINDSHIELD:
			print("WINDSHIELD chosen")
		Components.TIRES | Components.WHEEL:
			print("TIRES & WHEEL chosen")
		Components.TIRES | Components.WINDSHIELD:
			print("TIRES & WINDSHIELD chosen")
		Components.WHEEL | Components.WINDSHIELD:
			print("WHEEL AND WINDSHIELD chosen")
3 Likes