4

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

Community
  • 1
  • 1
Lucas
  • 3,517
  • 13
  • 46
  • 75
  • I don't think you want to sort your table inside the loop. Also, how exactly are you trying to sort it? `a[i]` is nil because `a` is a table with string indexes. – Omri Barel Jul 17 '11 at 19:51
  • Welcome to SO Lucas. When you need to clarify your question, use the edit button beneath you post rather than opening new questions. I'll flag the other two as duplicates of this one since I believe this Q&A best handles the problem. – BMitch Jul 17 '11 at 21:11
  • Similar question: http://stackoverflow.com/questions/2038418/associatively-sorting-a-table-by-value-in-lua – BMitch Jul 17 '11 at 21:17

1 Answers1

8

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436