Sorting by Functions in AngelScript

Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in AngelScript.

array<string> fruits = {"peach", "banana", "kiwi"};

// We implement a comparison function for string lengths.
int lenCmp(const string &in a, const string &in b)
{
    return a.length() - b.length();
}

// Now we can call sort with this custom comparison function to sort fruits by name length.
fruits.sort(lenCmp);
print(fruits);

// We can use the same technique to sort an array of values that aren't built-in types.
class Person
{
    string name;
    int age;
}

array<Person> people = {
    Person("Jax", 37),
    Person("TJ", 25),
    Person("Alex", 72)
};

// Sort people by age using a custom comparison function.
people.sort(function(const Person &in a, const Person &in b) {
    return a.age - b.age;
});

// Print the sorted array
for (uint i = 0; i < people.length(); i++)
{
    print(people[i].name + ": " + people[i].age);
}

In this AngelScript version:

  1. We use AngelScript’s built-in array type instead of slices.

  2. The custom comparison function lenCmp is implemented as a standalone function.

  3. We use the sort method on the array, which accepts a comparison function.

  4. For sorting the Person objects, we use an anonymous function directly in the sort method call.

  5. AngelScript doesn’t have a direct equivalent to Go’s fmt.Println for complex types, so we manually print each person’s details in a loop.

Note that AngelScript’s sorting is typically unstable, meaning that the relative order of equal elements may change. If a stable sort is required, you might need to implement it manually or use a more complex comparison that includes a secondary sort key.

This example demonstrates how to perform custom sorting in AngelScript, both for built-in types and user-defined classes.