How to loop a Dictionary in Godot C++ GDExtension?

  • xyz
    I digged a bit and got to this solution:

    Dictionary noise_generators = generator->get_noise_generators();
    Array keys = noise_generators.keys();
    
    for (int i = 0; i < keys.size(); i++)
    {
        Variant key = keys[i];
        Variant value = noise_generators[key];

    And from there I can work with key/value pairs.
    However, this is not ideal, since you'd expect to do a foreach entry in Dictionary, like so:

    for (Variant value : noise_generators)
    {
        // ...
    }

    But this is not supported, as shown here
    Thanks anyways!

I have zero practical experience with GDExtensions so I'm just taking a guess from looking at the Dictionary interface in Godot's source.

Get a list of keys in form of List<Variant> by calling Dictionary::get_key_list(). Now iterate this list and call Dictionary::get() or Dictionary::get_valid().

You can also just iterate integers from 0 to Dictionary::size() and call Dictionary::get_key_at_index() and Dictionary::get_value_at_index() to get key/value pairs.

Take a look at dictionary.h linked above. It's really self-explanatory.

    xyz
    I digged a bit and got to this solution:

    Dictionary noise_generators = generator->get_noise_generators();
    Array keys = noise_generators.keys();
    
    for (int i = 0; i < keys.size(); i++)
    {
        Variant key = keys[i];
        Variant value = noise_generators[key];

    And from there I can work with key/value pairs.
    However, this is not ideal, since you'd expect to do a foreach entry in Dictionary, like so:

    for (Variant value : noise_generators)
    {
        // ...
    }

    But this is not supported, as shown here
    Thanks anyways!

    • xyz replied to this.

      svrcrz It's pretty much what I suggested just written with overloaded [] operators.
      Yeah, iterator member functions begin() and end() are not implemented in the class so range based loops won't work.