Sorting By Functions in GDScript
Our example demonstrates how to implement custom sorting in GDScript. We’ll sort strings by their length and custom objects by a specific property.
extends Node
func _ready():
var fruits = ["peach", "banana", "kiwi"]
# We implement a comparison function for string lengths.
# GDScript doesn't have a built-in cmp function, so we'll create our own.
var len_cmp = func(a: String, b: String) -> bool:
return a.length() < b.length()
# Now we can call sort_custom with this custom comparison function
# to sort fruits by name length.
fruits.sort_custom(len_cmp)
print(fruits)
# We can use the same technique to sort an array of
# custom objects.
class Person:
var name: String
var age: int
func _init(n: String, a: int):
name = n
age = a
func _to_string():
return "{name: %s, age: %d}" % [name, age]
var people = [
Person.new("Jax", 37),
Person.new("TJ", 25),
Person.new("Alex", 72)
]
# Sort people by age using sort_custom.
people.sort_custom(func(a: Person, b: Person) -> bool:
return a.age < b.age)
print(people)
In this GDScript example, we’re using the sort_custom
method, which is similar to Go’s slices.SortFunc
. The sort_custom
method takes a comparison function as an argument.
For the string length comparison, we create a custom function len_cmp
that compares the lengths of two strings. We then use this function to sort the fruits
array.
For sorting custom objects, we define a Person
class with name
and age
properties. We then create an array of Person
objects and sort them based on their age
using another custom comparison function.
Note that in GDScript, unlike Go, the comparison function should return a boolean value: true
if the first argument should be sorted before the second, and false
otherwise.
When you run this script, you should see output similar to this:
["kiwi", "peach", "banana"]
[{name: TJ, age: 25}, {name: Jax, age: 37}, {name: Alex, age: 72}]
This demonstrates how we can implement custom sorting logic in GDScript, allowing us to sort both built-in types and custom objects according to specific criteria.