Sorting Using For loops

So I’m trying to make a function to sort the heights of players on a team and when i try to do so the value changes in the loop but doesnt actually change in the table.

local function SortHeights(Team)  print(Team)
		local PlrTable = {}
		local Heights = {}
		for i,v in pairs(Team) do print(Players[ i ].Character.Humanoid.BodyHeightScale.Value.." BodyHeightScale")
			table.insert(Heights,#Heights + 1,Players[ i ].Character.Humanoid.BodyHeightScale.Value)
			table.insert(PlrTable,#PlrTable + 1,{i, Players[ i ].Character.Humanoid.BodyHeightScale.Value,false})  
		end ; table.sort(Heights) ; print(PlrTable) ; print(Heights)
		for i,v in pairs(Heights) do 
			for i,PlrValues in pairs(PlrTable) do 
				if v == PlrValues[ 2 ] and not PlrValues[ 3 ] then
					PlrValues[ 3 ] = true
					v = {v,PlrValues[i]}  ; print(v)  -- when I print it it works and the value of v is changed 
				end
			end
		end
		print(Heights) -- when I print it here nothing has changed in the height/values. 
		return Heights
	end

You’re just overwriting the v variable and not actually changing the element inside the table.

Instead of

for i,v in pairs(Heights) do 
	for i,PlrValues in pairs(PlrTable) do 
		if v == PlrValues[ 2 ] and not PlrValues[ 3 ] then
			PlrValues[ 3 ] = true
			v = {v,PlrValues[i]}  ; print(v)
		end
	end
end

try

for i,v in pairs(Heights) do 
	for _,PlrValues in pairs(PlrTable) do 
		if v == PlrValues[ 2 ] and not PlrValues[ 3 ] then
			PlrValues[ 3 ] = true
			Heights[i] = {v,PlrValues[i]}  ; print(v)
		end
	end
end
2 Likes

Here’s an example.

local Table = {
	[222]	= 'Player1',
	[444]	= 'Player2',
	[777] 	= 'Player3',
	[1000]	= 'Player4'
}

table.sort(Table, function(a, b)
	return (a > b)
end)

for i, v in pairs(Table) do
	print(i, v)
end

-- This will give you the numbers (greatest to lowest.)

Good luck!

1 Like