如何在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.