How do I sort a multidimensional table in Lua?

孤街醉人 提交于 2020-01-30 05:43:05

问题


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

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


回答1:


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)

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.



来源:https://stackoverflow.com/questions/58500508/how-do-i-sort-a-multidimensional-table-in-lua

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