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

3
  • 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
    Commented Jul 17, 2011 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
    Commented Jul 17, 2011 at 21:11
  • Similar question: stackoverflow.com/questions/2038418/…
    – BMitch
    Commented Jul 17, 2011 at 21:17

1 Answer 1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.