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
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?
Thanks guys :)
Note that, for Lua, arrays also have no order.
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.
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.
table.sort
takes a comparison function as its second argument.
table.sort(distances, function (left, right)
return left[2] < right[2]
end)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With