table value sorting in lua

我是研究僧i 提交于 2019-12-24 11:06:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!