Reverse sort items with a numeric string key
How to sort numbers that you have to convert to strings — in reverse?!
The setup for this story is pretty elaborate, but hear me out.
In Godot script editor, there is a little side-window displaying your recently / currently open scripts. There is a few options for sorting them — by name, path or not sorting them at all. Internally, they are sorted by a string key.
I wanted to sort them by a modified date, which is a number — a uint64_t
to be precise. And in descending order, so that the newest ones would end up on top.
Normally, you would just sort with a different comparison function. This is absolutely the right thing to do, but this is the Godot engine. I didn’t want to just run around adding stuff, refactoring and breaking things. No no no. What I want is to slot into the existing infrastructure with the smallest possible change.
Ascending order
To try out what I had in mind, the first simple implementation had ascending order. This is the natural order. Converting the number to a string is easy enough, although this poses some challenges of its own:
- Negative numbers don’t really work.
- It’s in the wrong order, damn it