How is @export_flags meant to be used?

Godot Version

4.6

Question

I tried to use @export_flags for the first time, and am having trouble figuring out how it is meant to be used. I was expecting an int that I could use operators like & and | on like in C++. Instead I’ve getting a Variant and all my operators are failing to work the way I would expect them too.

The documentation on @export_flags only describes how to define them and provides no examples of how they are meant to be used in the body of the code. How am I supposed to use these?

You’d be right to expect an int given that flags are stored in bits. I’m not sure why you’re experiencing your problems though. I tried testing export flags, and it just worked with the following test code:

@export_flags("earth", "wind", "fire") var flag1
@export_flags("earth", "wind", "fire") var flag2

func _ready():
    var combined_flag = flag1 | flag2
    print("Combined flag value: %s" % combined_flag)

However, I do experience a Invalid operands 'Nil' and 'Nil' in operator '|' error. It looks like a variable with the @export_flags annotation doesn’t initialize itself; the error only occurs when the value(s) are not set in the inspector. If the variables are set to 0 (i.e. all flags are false), the code works as expected.

Not sure whether this actually should happen. GDScript is a dynamically typed language so the only way the code knows the type is when the variable is set to a specific value of a specific type – otherwise a type of Variant is probably assumed (which may be why you’re experiencing your error). Although, given that the inspector knows how to parse the variable as flags probably also means it should be capable of initializing it to a correct default value. I don’t know.

In any case, I fixed my issue by explicitly defining the variables’ type to int. Try to see if that doesn’t work for you as well.


Let me know if you have any other questions.

1 Like

How would you test flag1 to see if it has “fire” set? Just

var has_fire:bool = (flag1 & 0b100) != 0

Yes that would test the “fire” bit. you can give the variable int type similar to how you did for bool

@export_flags("earth", "wind", "fire") var flag1: int = 0

func has_fire() -> bool:
    return (flag1 & 0b100) != 0
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.