There is no built-in function to do this (the Lua standard library is very bare, and ROBLOX doesn't really add anything that deals with plain types like tables)
Here's an outline of how you might do it:
Given your list, build a map count where count[value] is the number of times that value appeared in list.
Implementation
function countMap(list)
local counts = {}
for _, value in ipairs(list) do
if counts[value] then
counts[value] = counts[value] + 1
else
counts[value] = 1
end
end
return counts
end
This can be shortened a bit, if you want:
function countMap(list)
local counts = {}
for _, value in ipairs(list) do
counts[value] = (counts[value] or 0) + 1
end
return counts
end
After we have the counts, we just need to find the key that has the largest value.
function keyLargest(map)
local best = nil
for key in pairs(map) do
if best == nil then
best = key
elseif map[best] < map[key] then
best = key
end
end
return best
end
This can be shortened a bit, if you want:
function keyLargest(map)
local best = next(map)
for key in pairs(map) do
if map[best] < map[key] then
best = key
end
end
return best
end
Then mostCommon can just be defined in terms of the above two functions:
function mostCommon(list)
return keyLargest(countMap(list))
end
Note that this will break ties arbitrarily, i.e., mostCommon{1, 1, 2, 2} could be either 1 or 2.
1 comment
You can either periodically count the amount of each group using a hashtable, or just add/subtract to a table when a player of a certain group joins/leaves. If you would like more details (or an example), let me know.