Wondering how I could construct a table that saves a player and their associated team once and properly clear it?

I want to improve upon my admittedly flawed reward system after a match ends. Currently it rewards good for people who are still alive and won (and also moderately for alive and lost–I digress), but what about the people who won and died? I have it set to where when a player dies they no longer are apart of their team and so they earn low amounts and this along with the fact that people can join a server with a match in progress and still earn rewards are both flaws.

I want to make it better–to where I ignore any new people joining i.e. make a table of current actual players at the start of the match, and then when the round ends, determine their current team (which assuming they have died they will be apart of “Lobby” Team AND are on the list I can determine what rewards would be given)

But I’m not sure how to properly store a player, their team, and clear the table. (Also would there be any bugs if a player leaves? It could result in a nil value if I do it this way)

Sample code:

for _,player in pairs (game.Players:GetPlayers()) do
if (win condition for team1) then
				if player.Team==team1 then
					GiveMoney:FireClient(100, player)
					GiveXP:FireClient(100, player)
				end
			if player.Team==team2 then
				GiveMoney:FireClient(60, player)
				GiveXP:FireClient(50, player)
				end
				else
				GiveMoney:FireClient(30, player)
				GiveXP:FireClient(25, player)
			end

Put simply, when you assign the players to their respective teams, store the team they were assigned to using a table. The table will map players to the team they were assigned to at the beginning of the game, and that can be your source of truth for your reward system.

Here’s what I mean:

-- Create a new table to store the team associations
local playerTeams = {}

-- During team assignment:
for _, player in pairs(game.Players:GetPlayers()) do
   local teamToAssign = chooseTeamForPlayer(player)
   -- First, set the Team property so they appear to be on that team
   player.Team = teamToAssign 
   -- Internally, save the association so we remember the team they were assigned
   playerTeams[player] = teamToAssign 
end

-- During end-of-round rewards:
for player, team in pairs(playerTeams) do
   if canBeRewarded(player) then -- Player should still be in-game (player.Parent ~= nil)
      if team == winningTeam then
         rewardPlayerForWinning(player) -- May have logic for whether they lived/died
      else
         rewardPlayerForParticipating(player)
      end
   end
end
1 Like