Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Arrays in Array in Lua

Hi i am quite new to lua and i need to sort an Array in Lua.

So i have following code

local distances = {2,3,1}
table.sort(distances)

now i get

  • distances[1] -> 1
  • distances[2] -> 2
  • distances[3] -> 3

now i need to save some information for my "distances" aswell something like the following

local distances = {{C1,2},{C2,3},{C3,1}}

now it is impossible to call the sort-function, but i need them sorted. Is it possible to reach this?

  • distances[1] -> {C3,1}
  • distances[2] -> {C2,2}
  • distances[3] -> {C1,3}

Thanks guys :)

like image 241
hannes Avatar asked Nov 29 '16 12:11

hannes


People also ask

Are Lua arrays ordered?

Note that, for Lua, arrays also have no order.

Is Lua 1 or 0 indexed?

Yes, the arrays in Lua start with index 1 as the first index and not index 0 as you might have seen in most of the programming languages.

How does table sort work Lua?

One of the most used functions in Lua is the sort function which is provided by the Lua library which tables a table as an argument and sorts the values that are present inside the table. The sort function also takes one more argument with the table and that argument is a function which is known as the order function.


1 Answers

table.sort takes a comparison function as its second argument.

table.sort(distances, function (left, right)
    return left[2] < right[2]
end)
like image 141
Oka Avatar answered Oct 31 '22 05:10

Oka