Jake
Jake

Reputation: 97

How do I sort a multidimensional table in 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}}

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

Upvotes: 3

Views: 705

Answers (1)

lubgr
lubgr

Reputation: 38267

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.

Upvotes: 4

Related Questions