Lucas
Lucas

Reputation: 3715

sorting a table in descending order in Lua

I can not get it work:

tbl = {
    [1] = { ['etc2'] = 14477 },
    [2] = { ['etc1'] = 1337 },
    [3] = { ['etc3'] = 1336 },
    [4] = { ['etc4'] = 1335 }
}

for i = 1, #tbl do
    table.sort(tbl, function(a, b) return a[i] > b[i] end)
    print(tbl[i] .. '==' .. #tbl)
end

Getting this error: attempt to compare two nil values

This is a follow-on to table value sorting in lua

Upvotes: 4

Views: 10912

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

How about this?

tbl = {
    { 'etc3', 1336 },
    { 'etc2', 14477 },
    { 'etc4', 1335 },
    { 'etc1', 1337 },
}

table.sort(tbl, function(a, b) return a[2] > b[2] end)

for k,v in ipairs(tbl) do
    print(v[1], ' == ', v[2])
end

Organizing the data that way made it easier to sort, and note that I only call table.sort once, not once per element of the table. And I sort based on the second value in the subtables, which I think is what you wanted.

Upvotes: 8

Related Questions