lua中的表值排序

发布于 2024-11-24 18:15:48 字数 369 浏览 2 评论 0原文

我有一个像这样的表:

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

现在我需要对该表进行排序以获得从最高值到最低值的输出:

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

已经尝试了很多功能,例如 table.sort 或官方手册中的其他功能,但没有任何帮助。所以希望你们能帮助我!

问候。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人 2024-12-01 18:15:48

Lua 表除了通过键之外没有排序。 您将需要更像这样构造您的数据:

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

或这样:

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

如果您想将其与原始表结合使用,

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

或这样:请注意,我非常明确并编写了所有数字索引。您当然可以省略它们,所以最后的解决方案是:

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

也许这意味着您应该编写一个函数将原始数据转换为新的形式,或者您可以在第一个表创建之前提前完成它地方。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文