lua中的表值排序

编程入门 行业动态 更新时间:2024-10-25 10:29:29
本文介绍了lua中的表值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一张这样的桌子:

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 }

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

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!

致谢.

推荐答案

Lua表除通过其键进行排序外没有其他排序.您将需要像这样更结构化数据:

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 } }

或者这个:

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.

更多推荐

lua中的表值排序

本文发布于:2023-10-16 00:06:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!