This script doesn’t, work. What did I do wrong? lives = 3, but it doesn’t do lives > 1
local players = {}
Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(character)
character:WaitForChild("Humanoid").Died:Connect(function()
if #players > 0 then
for i, v in pairs(players) do
if v[plr.Name] then
local lives = v[plr.Name]
if lives > 1 then
lives = lives - 1
else
if plr.TeamColor == game.Teams.Alive.TeamColor then
plr.TeamColor = game.Teams.Lobby.TeamColor
end
end
end
end
else
table.insert(players, {[plr.Name] = 3}) -- Amount of lives
end
end)
end)
end)
I is the index of the player, it also doesn’t have any reason to have a check at all. You don’t need to use table.insert, instead I would recommend
players[plr.Name] = 3
This is because table.insert() inserts it like an array, if you’re creating a dictionary/object on the other hand, indexing directly works just fine. It also deletes the need entirely to have a loop at all. Instead you can just get the index, which is the player’s name and it’ll work perfectly.
Your table now uses strings instead of integers as it’s index.
#players will always return 0 in this case.
You don’t need the loop. You just need to directly check if players[plr.Name] exists or not. If it does, reduce the count, if it doesn’t, initialise it to 3.
It’s important to understand why this didn’t work, and the difference between arrays and dictionaries, hence my reply here that seems to have been ignored.
However, I think you are overcomplicating it for yourself and dealing with a table (with potential memory leaks if you don’t remove players’ entries) is not necessary at all.
Try using Attributes, as shown in the example below:
game.Players.PlayerAdded:Connect(function(plr)
plr.CharacterAdded:Connect(function(character)
character:WaitForChild("Humanoid").Died:Connect(function()
local lives = plr:GetAttribute( 'Lives' )
if lives then
-- Take a life away
lives -= 1
plr:SetAttribute( 'Lives', lives )
-- Check if any lives remain
if lives < 1 then
-- No lives left
if plr.TeamColor == game.Teams.Alive.TeamColor then
plr.TeamColor = game.Teams.Lobby.TeamColor
end
end
else
-- Initialise the lives
plr:SetAttribute( 'Lives', 3 )
end
end)
end)
end)