11

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 :)

0

1 Answer 1

18

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

table.sort(distances, function (left, right)
    return left[2] < right[2]
end)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.