gaerzi wrote:But if I try to use rpairs instead, it complains about an "attempt to compare two nil values".
I don't actually have the code up, but, if I recall correctly, my rpairs is similar to the 'spairs' code you linked, but the sorting function works differently. In the code you linked, the sorting function is passed a table and 2 keys. In my 'rpairs', I believe the sorting function is just passed 2 keys, so if you want to reference the source table, you need to capture it as an upvalue from your sort function definition.
My 'spairs' functions works sortof similarly. (Though that one doesn't even accept an optional custom sorting function.) Um, I actually got in a big conversation on the Lua mailing list about all these sorts of details almost 10 years ago -- you can still read through the
threads if you want to learn more about all the technicalities that come up with this sort of stuff.