openlang

Choosing enum entries randomly with GDScript in Godot 3.3 without listing each one?

Here's the enum declaration I'm using in GDScript:

enum Motion = { IDLE, STEPPING, DASHING }

I'd like to choose an enum variant randomly without listing every possible variant, allowing me to introduce additional variants later without needing to edit the code that makes the random selection.

Here's one approach I've tried:

Motion.get(randi() % Motion.size())

And another:

Motion[randi() % Motion.size()]

Both fail. One returns Null, while the other reports "Invalid get index '1' (on base: 'Dictionary')."

What's a way of achieving this that will actually work?

The conversation continues 2

Follow the reasoning
  1. Permalink

    You can accomplish it with this expression:

    Motion.keys()[randi() % Motion.size()]

    It works since keys() turns the Motion dictionary into an array, letting you access entries with [].

Other sides of the same question

  1. Empty reductions return the identity

    Reduce over an empty vector. APL answers. Each primitive carries its identity. Zero for plus. One for times and for and. ⌈/⍬…

    Replies 3Latest activity apl
  2. Can Gleam lists be indexed backwards from their last element?

    I need to separate strings containing different numbers of - delimiters. I want the fourth item counting backwards, ignoring…

    Replies 2Latest activity gleam
  3. Most of my macros turned into const and static

    Nim makes macros easy to write. That's the problem. Before reaching for macro, check the cheaper tools. A const is evaluated…

    Replies 3Latest activity nim