12

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

19

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

table.sort(distances, function (left, right)
    return left[2] < right[2]
end)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.