Map (table/array) sorting

A place for discussion of making game modifications.
gaerzi
Posts: 210
Joined: Wed Jul 10, 2019 1:30 pm

Map (table/array) sorting

Postby gaerzi » Sun Aug 01, 2021 12:12 pm

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".

User avatar
sven
Site Admin
Posts: 1621
Joined: Sat Jan 31, 2015 10:24 pm
Location: British Columbia, Canada
Contact:

Re: Map (table/array) sorting

Postby sven » Mon Aug 02, 2021 6:05 am

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.

gaerzi
Posts: 210
Joined: Wed Jul 10, 2019 1:30 pm

Re: Map (table/array) sorting

Postby gaerzi » Mon Aug 02, 2021 10:55 am

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.


Return to “Modding”

Who is online

Users browsing this forum: No registered users and 24 guests