Topic was automatically imported from the old Question2Answer platform.
Asked By
BigDC
I use Godot 3.
Hello,
Lets’s say I have the following array and it is structured like this…
slots[0] = “”
slots{1] = 11
slots[2] = 1
slots[3] = “”
slots[4] = 4
But I need some type of code that ill actrually sort the array structure so it ends up like this instead…
slots[0] = 1
slots{1] = 4
slots[2] = 11
slots[3] = “”
slots[4] = “”
func _ready():
var arr = ["",11,1,"",4]
arr.sort_custom(self, "customComparison")
print (arr)
func customComparison(a, b):
if typeof(a) != typeof(b):
return typeof(a) < typeof(b)
else:
return a < b
This code depends on integer values assigned to types. Currently int is 2 and string is 4. If it ever changes, which is doubtful, results can be different.
Edit:
And here’s code that allows to specify order of types in sorting:
const TypeOrder = [TYPE_STRING, TYPE_INT]
func customComparison2(a, b):
if typeof(a) != typeof(b):
if typeof(a) in TypeOrder and typeof(b) in TypeOrder:
return TypeOrder.find( typeof(a) ) < TypeOrder.find( typeof(b) )
else:
return typeof(a) < typeof(b)
else:
return a < b
In this case strings are before integers.
Arrays are sorted in place.
arr.sort()
turns arr into a sorted array.
it doesn’t return the array so you don’t need to do