Repost since the last post didn’t get any answers.
So I’m making a voting system for my game, and I’m struggling to get the table with the most values.
How my system works is that it adds a player to a table each time a player a player steps on a pad, and fires a remote to the client to activate the pad to their screen so it doesn’t show to ever single player.
local voters = {} -- list of tables with players that voted
table.insert(voters[index], player) -- add the player to the table for the option they choosed
If you’re using separate tables for each vote, you can just use #tablename and it will return the number of values in said table, e.g:
local voteOne = {}
table.insert(voteOne, player)
print(#voteOne) -- in this case, it would print: "1"
You would then compare these values to the other vote tables and see which has the highest value, for example:
local voteOne = {}
local voteTwo = {}
local voteThree = {}
for i = 1,10 do
table.insert(voteOne, "placeholder")
table.insert(voteTwo, "placeholder")
end
for i = 1,11 do
table.insert(voteThree, "placeholder")
end
if #voteOne > #voteTwo and #voteOne > #voteThree then
print("Vote one wins")
elseif #voteTwo > #voteOne and #voteTwo > #voteThree then
print("Vote two wins")
elseif #voteThree > #voteTwo and #voteThree > #voteOne then
print("Vote three wins")
else
print("Not enough votes or draw")
end
If you have additional votes then it would be more efficient to put them into a dictionary and sort them to find the highest key-value pairs.
Sorry I’m half asleep, you could assign the player as the index and add their vote of choice to the value to tally up:
local voters {}
local voteOne = 0
local voteTwo = 0
local function PlayerVote(player, voteChoice)
voters[player] = voteChoice
end
for _,v in pairs(voters) do
if v = "voteOne" then
voteOne += 1
elseif v == "voteTwo" then
voteTwo += 1
end
end
local table1 = {
val;
val;
val;
};
local table2 = {
val;
val;
};
if #table1 > #table2 then
print(#table1)
elseif #table2 > #table1 then
print(#table2)
end
local voters = {
{}, {}, {}, {}
}
-- fill tables with random amount of players
for i, t in ipairs(voters) do
t.name = "Table " .. i
for i = 1, math.random(2, 6) do
table.insert(t, "player")
end
print(string.format("Table %d has %d votes", i, #t))
end
--
local highestVote = #voters[1]
local voteWinners = {}
-- get highest number of votes from all tables
for i = 2, #voters do
local votes = #voters[i]
highestVote = math.max(highestVote, votes)
end
print("Highest vote:", highestVote)
-- insert all tables with the highest number of votes
-- into the winners table (in case of ties)
for i, t in ipairs(voters) do
if #t == highestVote then
table.insert(voteWinners, t)
end
end
-- you don't need this part either,
-- this is just for you to see visually
if #voteWinners > 1 then
warn(string.format("Picking random winner from %d total winners", #voteWinners))
end
local voteWinner = voteWinners[math.random(#voteWinners)]
print(voteWinner.name, "is the picked winner")