Attempt to compare Instance < Instance table.insert()

here’s the code:

local checkpoints = {}
for _, index in pairs(script.Parent.CheckPoints:GetChildren()) do
	if index:IsA("BasePart") then
		table.insert(checkpoints, index)
		end
end
table.sort(checkpoints)
for _, test in ipairs(checkpoints) do
	print(test)
end

image

Simply at Surround checkpoints into a table

table.sort({checkpoints})

if you wanted a array

local checkpoints = {}
for number, index in pairs(script.Parent.Checkpoints:GetChildren()) do
	if index:IsA("BasePart") then
		checkpoints[number] = index -- Assigns a Variable within the Table as the Item
	end
end
for name, value in ipairs(checkpoints) do
	print(name, value) -- 1, Checkpoint1  2, Checkpoint2
end
1 Like

table.sort is trying to compare two instances with a < operator
Instead you need to pass a function to table.sort and provide a true/false

local function GetIntFromCheckpoint(Checkpoint: Instance)
	return tonumber(string.sub(Checkpoint.Name, 11))
end

local checkpoints = {}
for _, index in pairs(script.Parent.CheckPoints:GetChildren()) do
	if index:IsA("BasePart") then
		table.insert(checkpoints, index)
	end
end

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

for _, test in ipairs(checkpoints) do
	print(test)
end

This will get the numbers at the end of the checkpoints name and compare the numbers

2 Likes

Could you explain to me why we have stuff in parenthesis?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.