How to use enum value as dictionary key in GDScript

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

Is it possible to use enum values as dictionary keys in GDScript? I have some code that does the following to setup directional movement. However, when I try to access a value in the dictionary, I get the error “Invalid get index ‘RIGHT’ (on base: ‘int’).” Is this just not allowed? Thanks!

enum Direction {
    RIGHT,
    LEFT,
    UP,
    DOWN
}

var movementVectors = {
    Direction.RIGHT: Vector2.RIGHT,
    Direction.LEFT: Vector2.LEFT,
    Direction.UP: Vector2.UP,
    Direction.DOWN: Vector2.DOWN
}

var direction = Direction.RIGHT

# Gives me the error Invalid get index 'RIGHT' (on base: 'int').
var movementVector = movementVectors[direction]
:bust_in_silhouette: Reply From: kidscancode

This code works perfectly fine. The error says “on base: ‘int’” - that’s nothing to do with dictionary keys - it means you’re trying to use [] on an integer variable.

Maybe you wrote movementVector[direction] (leaving off the “s”)?

:bust_in_silhouette: Reply From: 1shevelov

Try this syntax to use enum values as properties’ names

var movementVectors = {}
movementVectors[Direction.RIGHT] = Vector2.RIGHT
movementVectors[Direction.LEFT] = Vector2.LEFT