I have a iterator that gets the magnitudes of various minor points from a centralized major point.
I currently just insert these into a table. But I want them to be ordered by their values least to greatest.
I know I can find a way with sort, but I was wondering if I even have to do this; is there a way I can instead automatically put them in the table in a way that would just be already sorted as intended at insertion time?
You can only use table.sort if your table is an array. Otherwise you will have to use a loop to go through all of the tables contents to sort them into a new table. I wouldn’t recommend overcomplicating anything.
You can also pass a custom sort function into table.sort.
Assuming your array values are Vector3s:
local center = (center point)
local points = {(other points)}
-- A custom sort function is made to return true when element A comes before element B in the array.
local function distanceSort(a, b)
return (a - center).Magnitude < (b - center).Magnitude
end
table.sort(points, distanceSort)
Thank you everyone, constructive and insightful takes! I ended up just using a custom sort pred function that takes the two as array values and compares their first index value, which stores the magnitude.