Page 1 of 1

Map (table/array) sorting

Posted: Sun Aug 01, 2021 12:12 pm
by gaerzi
So I'm trying to get a list of key=value sorted by order of decreasing value, and I can't seem to find out how to do that with the available functions from iterators.lua.

Keep in mind that I'm really not an expert in Lua, as I barely understand its syntax. So I've adopted the spairs function found here (renamed as "zpairs" so as to avoid interfering with existing code that calls upon spairs).

So when I have

Code: Select all

   for race, p in zpairs(empire_pop, function(t,a,b) return t[b] < t[a] end)

it works.

But if I try to use rpairs instead, it complains about an "attempt to compare two nil values".

Re: Map (table/array) sorting

Posted: Mon Aug 02, 2021 6:05 am
by sven
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.

Re: Map (table/array) sorting

Posted: Mon Aug 02, 2021 10:55 am
by gaerzi
sven wrote:you need to capture it as an upvalue from your sort function definition.


I don't grok Lua enough to know how to do that (all my attempts ended in various error messages) so I'll just keep my zpairs for now.