I want to make something like a voting system or a GUI that displays who has the most kills, but what I don’t know is how to find the greatest number out of multiple number values. Can someone explain how this is done?
Using table.sort
is okay, but inefficient. You're doing a needlessly expensive operation when a single loop through of the list is sufficient.
If you want to find the maximum of a list of numbers, use
math.max(unpack(list))
Note that this will only work if the list is less than 8000 elements big, and if they're all numbers.
If you're dealing with more complicated data types / structures, or if you want to deal with longer lists, you're going to have to get a bit fancier.
function findMax(list, comparator) comparator = comparator or math.max currentMax = list[1] for v in pairs(list) do currentMax = comparator(currentMax, v) end return currentMax end
This should do what you want. Using it in the simple case is easy. If comparator
is left blank when calling it, it will default to standard math.max
behaviour:
a = {1, 2, 3, 4} b = findMax(a) print(b) -- Gives 4
What about if we have a list of players, and we want to find the one with the highest score?
players = game:GetService("Players"):GetPlayers() highScorer = findMax(players, function(playerA, playerB) if playerA.leaderstats.Score.Value > playerB.leaderstats.Score.Value then return playerA else return playerB end end))
Basically, comparator
is any function which takes two values and returns the largest.
For example, if we wanted to select the heaviest brick:
function heaviestComparator(a, b) if a:GetMass() > b:GetMass() then return a else return b end end heaviestBrick = findMax(bricks, heaviestComparator)
you can use math.max()
which returns the greatest value of them given, though it isnt only limited to 2 values but can store multiple (3, 4, 6, 11...), since it uses variadic arguments.
local num1 = 16 local num2 = 25 local hum3 = 6 print(math.max(num1,num2,num3)) -- prints 25
For a gui that displays who has the most of any score, math.max is the most efficient method, but if you want to display, say the top 3, 5 , or 10, something on the lines of table.sort()
.
What table.sort does is sort/organize a table using its default procedure which is <
. However, that can be changed like such:
local kos = {1,421,32} table.sort(kos,function(a,b) return a>b end) for _, plrKos in next, kos do print(plrKos) end--421,32,1