如何在Lua中对多维表进行排序? [英] How do I sort a multidimensional table in Lua?

查看:93
本文介绍了如何在Lua中对多维表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本上包含以下内容的表格:

I have a table consisting basically of the following:

myTable = {{1, 6.345}, {2, 3.678}, {3, 4.890}}

,我想按十进制值对表格进行排序. 所以我希望输出为:

and I'd like to sort the table by the decimal values. So I'd like to the output to be:

{{2, 3.678}, {3, 4.890}, {1, 6.345}}

如果可能的话,我想使用table.sort()函数.预先感谢您的帮助:-)

If possible, I'd like to use the table.sort() function. Thankyou in advance for the help :-)

推荐答案

鉴于您的表是一个序列,您可以直接使用table.sort.此函数接受比较谓词作为其第二个参数,它规定了比较逻辑:

Given that your table is a sequence, you can use table.sort directly. This function accepts a comparison predicate as its second argument, which prescribes the comparison logic:

require 'table'

myTable = {{1, 6.345}, {2, 3.678}, {3, 4.890}}

table.sort(myTable, function(lhs, rhs) return lhs[2] < rhs[2] end)

打印表格如for _, v in ipairs(myTable) do print(v[1], v[2]) end所示,则显示所需的顺序:

Printing the table e.g. as for _, v in ipairs(myTable) do print(v[1], v[2]) end then shows the desired ordering:

2       3.678
3       4.89
1       6.345

这里的关键不是要排序的表的维度,而是它是序列(即有序的)的事实.

They key here is not the dimension of the table to sort, but the fact that it is a sequence, i.e. ordered.

这篇关于如何在Lua中对多维表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆