I stumbled on this problem during my current project and am looking for suggestions on how to achieve it in GDScript.
I want to sort objects in an array based on properties I can access through the objects get functions. I know I can write a custom sort function for a specific property, e.g. health
, like this:
func custom_sort(a, b):
return a.get_health() < b.get_health()
And I can use it on an array arr
by calling arr.sort_custom(self, 'custom_sort')
.
In my project, I now need to dynamically sort objects by different properties, the get functions of which sometimes require additional parameters. Because there are many properties, what I would really want to have is a custom sort function that can take the get function and its parameters as parameters, something like this:
func custom_sort(a, b, property: String, parameters: Array=[]):
return a.call(property, parameters) < b.call(property, parameters)
(I know call()
would actually require the parameters as a comma-separated list, but since this isn't the problem here, let's just ignore this part)
However, it seems custom sort functions cannot take additional parameters, and there is no way to pass parameters to them anyway in the arr.sort_custom()
call.
The only other approach short of manually defining a custom sort function for every property I want to sort by is somehow constructing an appropriate custom sort function in code and then passing it to arr.sort_custom()
. Based on my understanding, GDScript doesn't have first-class functions though, and while I could use func_ref()
to reference and pass a function, I cannot construct one from code.
So is there any other way of achieving this behavior? Or is there any way to circumvent this problem entirely (without manually defining all custom sort functions, of course)?