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.