1

I got an table like this:

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

And now I need to sort this table to get output from highes to lowest value:

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

Already tried lots of functions like table.sort or others from the official manual, but nothing helped. So hope you'll help me out guys!

Regards.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Lucas
  • 3,517
  • 13
  • 46
  • 75
  • @mods, sorry, I submitted the flag too soon, this is a duplicate of http://stackoverflow.com/questions/6726130/lua-desc-sorting-table-problem – BMitch Jul 17 '11 at 21:13

1 Answers1

1

Lua tables do not have ordering other than by their keys. You will need to structure your data more like this:

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

or this:

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

or this, if you want to use it in conjunction with the original table:

tbl_keys = {
    [1] = 'etc2',
    [2] = 'etc1',
    [3] = 'etc3',
    [4] = 'etc4'
}

Note that I was very explicit and wrote all the numeric indices. You can of course omit them, so the last solution would be:

tbl_keys = {
    'etc2',
    'etc1',
    'etc3',
    'etc4'
}

Maybe this means you should write a function which turns the original data into this new form, or maybe you can get it done earlier on, before the table is made in the first place.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Well. I am creating my table in this way: dmg = {} if not dmg[attacker] then dmg[attacker] = value else dmg[attacker] = dmg[attacker] + value end So, how can I change it so output can look's like one of your example? fe. : tbl = { [1] = { ['etc2'] = 14477 }, [2] = { ['etc1'] = 1337 }, [3] = { ['etc3'] = 1336 }, [4] = { ['etc4'] = 1335 } } Regards. – Lucas Jul 17 '11 at 18:38
  • Why don't you try it and post a new question if you get stuck? – John Zwinck Jul 17 '11 at 18:43
  • I see you posted it here: http://stackoverflow.com/questions/6726130/lua-desc-sorting-table-problem – John Zwinck Jul 17 '11 at 19:37