How to sort array using lambda in GDExtension

Godot Version

4.2.1

Question

In GDscript you can sort array using lambda like this:
my_items.sort_custom(func(a, b): return a[0] > b[0])

But how do I do the same using GDExtension?

1 Like

I don’t believe there’s much support for lambdas. The comparator function for variants has to be in a registered class so a valid callable can be made and passed to the sort function. I don’t believe the Godot template classes take lambda arguments either.

I’ve built an example for the two in case you may want it, but none of these sort functions take lambda arguments.

example_sort.h
#ifndef EXAMPLESORT_H
#define EXAMPLESORT_H

#include <godot_cpp/classes/node.hpp>

#include <godot_cpp/templates/vector.hpp>
#include <godot_cpp/variant/array.hpp>

using namespace godot;

class ExampleSort : public Node {
	GDCLASS(ExampleSort, Node)

private:
	Vector<int> template_array;
	Array variant_array;

	// The comparator for template_array, which uses a template for sort_custom
	struct TAComparator {
		bool operator()(int a, int b) const {
			return a < b;
		}
	};

	// The comparator for variant_array, which takes a callable for sort
	bool va_comparator(int a, int b) {
		return a < b;
	}

protected:
    static void _bind_methods();
    void _notification(int p_what);

public:
	ExampleSort();
};

#endif // EXAMPLESORT_H
example_sort.cpp
#include "example_sort.h"

#include <godot_cpp/classes/engine.hpp>
#include <godot_cpp/classes/random_number_generator.hpp>

#include <godot_cpp/variant/utility_functions.hpp>

void ExampleSort::_bind_methods() {}

void ExampleSort::_notification(int p_what) {
	switch (p_what) {
		case (NOTIFICATION_READY): {
			RandomNumberGenerator rng;

			// Add random numbers to arrays
			for (int i = 0; i < 32; i++) {
				int j = rng.randi_range(0, 64);
				template_array.append(j);
				variant_array.append(j);
			}

			UtilityFunctions::print("Unsorted: ", variant_array);

			// Sort arrays
			template_array.sort_custom<TAComparator>();
			variant_array.sort_custom(callable_mp(this, &ExampleSort::va_comparator));

			UtilityFunctions::print("Sorted: ", variant_array);
		}
	}
}

ExampleSort::ExampleSort() {}

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