问题
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.
回答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.
来源:https://stackoverflow.com/questions/6725707/table-value-sorting-in-lua