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.
In this AngelScript version:
We use AngelScript’s built-in
array
type instead of slices.The custom comparison function
lenCmp
is implemented as a standalone function.We use the
sort
method on the array, which accepts a comparison function.For sorting the
Person
objects, we use an anonymous function directly in thesort
method call.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.