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

How do I organize a table of numbers from least to greatest?

What I'm trying to do is at the end of the round in my game, I want a list of every player's kills in order, but so far I only found out how to find the player with the most/least of a certain value. Any help will be appreciated!

1 answer

✓ Accepted answer

There is a table method called sort. This method takes the table (t), and an optional function to provide an algorithm for sorting.

A requirement for the comp function is two arguments. The function should return true when the first element should come before the second.

An example of a sorting function (comp) is:

local nums = {1, 5, 2, 3, 7, 5, 8, 9, 1}

local sortFunction = function(n1,n2)
	if n1 < n2 then
		return true
	elseif n1 > n2 then
		return false
	end
end

table.sort(nums,sortFunction)

for _,v in pairs(nums) do
	print(v)
end

-- Output:
-- 1 (x2)
-- 2
-- 3
-- 5 (x2)
-- 7
-- 8
-- 9

The above function sorts the table from least to greatest.

void table.sort ( array t, function comp = nil )

To organize something like a player's kills from least to greatest, you could use a comp function like this:

local sortFunction = function(player1,player2)
	if player1.kills.Value < player2.kills.Value then
		return true
	elseif player1.kills.Value > player2.kills.Value then
		return false
	end
end

Note: When posting a question, you should provide your own code that we can help you with.

1 comment

0

Oh my gosh! Thanks so much

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