Help with table.sort

Hello! i want to make checkpoints where a part moves to it (tween) in order:
image
i want to use a table since it has the ability to sort it.
heres what i came up with:
find the lines where there is --!!

wait(2)
--> General var
local rootPart = script.Parent.RootPart

--> Gets robot's Y Position
local currentYPos = {}
if not table.find(currentYPos, rootPart) then
	currentYPos[rootPart] = rootPart.Position.Y
end
local yPos = currentYPos[rootPart]
local addY = Vector3.new(0,yPos,0)

--> Tween settings
local tweenService = game:GetService("TweenService")
local instance = rootPart

--> Applys tweens
local folder = workspace.Folder
local checkpoints = {}

for i,checkpoint in pairs(folder:GetChildren()) do
	if checkpoint then
		table.insert(checkpoints, checkpoint.Name) --!!
		table.sort(checkpoints) --!!
		print(checkpoint.Name)

		local tweenInfo = TweenInfo.new((rootPart.Position - checkpoint.Position).Magnitude/30, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)

		rootPart.CFrame = CFrame.new(rootPart.Position, checkpoint.Position)
		rootPart.CFrame = rootPart.CFrame:ToWorldSpace(CFrame.Angles(0, math.rad(-180), 0))
		rootPart.Orientation = Vector3.new(0,rootPart.Orientation.Y, rootPart.Orientation.Z)
		
		local goals = {}
		local goalPosition = {Position = checkpoint.Position + addY}
		
		table.insert(goals, goalPosition)
		for i = 1, #goals do
			local tweenPosition = tweenService:Create(instance, tweenInfo, goals[i])
			tweenPosition:Play()
			tweenPosition.Completed:Wait(1)
		end
	end
end

i printed out the names to see the order and it gives me this, which isn’t in the order i expected:
image

You can use an optional comparator function for table.sort and string.byte to ensure that the parts are arranged in alphabetical order - since the ASCII byte representation of lower case characters are in order.

table.sort(checkpoints, function(a, b)
     return string.byte(a) < string.byte(b)
end)

More elegantly in your case:

local parts = folder:GetChildren()
table.sort(parts, function(p1, p2)
    return string.byte(p1.Name) < string.byte(p2.Name)
end)

for _, part in ipairs(parts) do
   print(part.Name) -- parts array is sorted in order
end

Alternatively, since there are only four parts, you can manually order them as well.

For words, however, you would have to compare each character, and so requires an iteration over one string and potentially multiple comparisons with the other.

table.sort(checkpoints, function(left, right)
	return left.Name < right.Name
end)

I just responded to a thread facing a similar issue.

1 Like