How would I do this?

I’m trying to make a ordered list of parts, but the parts numerical placement in the table will be dependent on the magnitude of a starting point. How would I do this?

This is what I have so far.

local e = workspace.eeee
local Waypoints = workspace.Waypoint

local OrderedWaypoints = {}
local waypointDistances = {}
local startWaypoint = Waypoints:WaitForChild("RailWaypointStart")
local endWaypoint = Waypoints:WaitForChild("RailWaypointEnd")

for i, v in pairs(Waypoints:GetChildren()) do
	if v.Name == "RailWaypoint" then
		table.insert(waypointDistances, (startWaypoint.Position - v.Position))

for i, v in pairs(waypointDistances) do -- Where I'm going to order the parts

You can use table.sort to, well, sort the table.

This should work.

table.sort(waypointDistances, function(A, B) 
    return A.Magnitude < B.Magnitude

--do whatever under this line

Never knew that table.sort existed O.o

Could you explain how the script exactly works though?

The documentation can explain it infinitely better than I can table | Roblox Creator Documentation

TL;DR: table.sort takes a function to compare 2 parameters: A, and B.

A is the object to compare to B.
If A is a lower number than B, then it is given a lower index than B, thus sorting it.

1 Like

Is there a way for me to just return the parts in order that is closer than other parts in the same group? Because it only sorts their positions, but doesn’t tell me there names.

table.sort(waypointDistances, function(A, B) 
    return A < B

Instead of sorting a list of distances, you’ll want to sort a list of parts like so:

local railroadWaypoints = {}

for _,child in Waypoints:GetChildren() do
	if child.Name == "RailWaypoint" then
		table.insert(railroadWaypoints, child)

table.sort(railroadWaypoints, function(a, b)
	local aDistanceFromStartWaypoint = (startWaypoint.Position - a.Position).Magnitude
	local bDistanceFromStartWaypoint = (startWaypoint.Position - b.Position).Magnitude
	return aDistanceFromStartWaypoint < bDistanceFromStartWaypoint

With the sorted list of parts, you could then do something like this:

for index,waypoint in railroadWaypoints do
	print(index, waypoint.Name)