Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 3 years ago

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

Log in to vote
3
Answered by
appxritixn 2235 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

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.

0
Oh my gosh! Thanks so much rubixxman 4 — 3y
Ad

Answer this question