Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can i sort the second value of a table?

I need the table Ores to be sorted but the first value is an object and i need it to be sorted by the Magnitude wich is the second value

	for _, Ore in pairs(SpotObjects:GetChildren()) do
		if Ore:IsA("BasePart") then
			if Ore.Lvl1.Transparency == 0 then
				OreMagnitude = (HumanoidRootPart.Position - Ore.Position).Magnitude 	
				Ores[Ore] = OreMagnitude
			end
		end
	end
	table.sort(Ores)
	for OresObject, i in pairs(Ores) do
		print(OresObject, i)
	end    

When i do print its not printing it in order

1 answer

✓ Accepted answer

table.sort does not work on dictionaries; infact it is impossible to sort dictionaries. If your goal's to end up with an ore array sorted close to far, I have a better script:

local RootPart = --?
local ores = {}
--create arbitrary array of ores
for _,ore in ipairs(SpotObjects:GetChildren()) do
	if ore:IsA("BasePart") and ore.Lvl1.Transparency==0 then
		ores[#ores+1]=ore
	end
end

--custom sort; sort() takes an optional function which manually compares values
--think of the default function as: function(a,b) return a < b end

table.sort(ores,function(ore1,ore2)
	--comparing magnitudes will sort by distance
	local mag1 = (ore1.Position-RootPart.Position).magnitude
	local mag2 = (ore2.Position-RootPart.Position).magnitude
	--you can flip the "<" to sort greatest-to-least
	return mag1 < mag2
end)

print(unpack(ores))

might be typos but I hope you get it. (pls dont simply ignore like some ppl e.e)

This discussion is preserved as it was. New answers, comments, and votes are closed.