Table is mysteriously cleared?

For quite a while now, I’ve had this problem where a table, “q1plrs”, is randomly cleared. There is no code clearing the table except for the function, “endGame”, but print statements indicate it happens before the function is called. It’s also worth mentioning that the code works swiftly the 1st round but is cleared after the player dies in the 2nd round. What is causing the table to be cleared? Any help is appreciated, thanks in advance!

Entire Script:

local q1 = script.Parent.q1
local q2 = script.Parent.q2

local Type = script.Type.Value

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local canStart = true

local UpdateRoundIntroText = ReplicatedStorage:WaitForChild("UpdateRoundIntroText")

local currentRound = 1
local totalRounds = 3

local Q1Points = 0
local Q2Points = 0

local Jumpable = true

local function isPointInZone(point, zonePart)
    local relPoint = zonePart.CFrame:PointToObjectSpace(point)
    return math.abs(relPoint.X) < zonePart.Size.X * 0.5 and math.abs(relPoint.Z) < zonePart.Size.Z * 0.5
end

function findnextbutton(currentPos)
	local nextbuttonpos = currentPos + 1
	for i,v in ipairs(script.Parent.q1:GetChildren())do
		if v.pos.Value == nextbuttonpos then
			return v
		end
	end
	for i,v in ipairs(script.Parent.q2:GetChildren())do
		if v.pos.Value == nextbuttonpos then
			return v
		end
	end
end

function findprevbutton(currentPos)
	local prevbuttonpos = currentPos - 1
	for i,v in ipairs(script.Parent.q1:GetChildren())do
		if v.pos.Value == prevbuttonpos then
			return v
		end
	end
	for i,v in ipairs(script.Parent.q2:GetChildren())do
		if v.pos.Value == prevbuttonpos then
			return v
		end
	end
end

function buttonTouched(part)
	game:GetService("RunService").Heartbeat:Connect(function()
		if canStart then
		for _,plr in pairs(game.Players:GetChildren()) do 
			local atzone = isPointInZone(plr.Character.PrimaryPart.Position, part)
			if part.plr.Value == "n/a" then
				if atzone == true and part.enabled.Value == true then
					withinzone(part,plr)
				else
					notwithinzone(part,plr)
				end			
			else -- if there is a player (if part.plr.Value ~= nil) 
				if plr.Name == part.plr.Value then
					if atzone == true and part.enabled.Value == true then
						withinzone(part,plr)
					else
						notwithinzone(part,plr)
					end
				end
			end
		end
		end
	end)
end

function playerLabel(part, plr, order)  --[ 0 = find and remove label ,  1 = create a label ] (regards to order)
	local num = tonumber(part.pos.Value) -- string patterns, testing if it is odd or even for q1 or q2
	local rem = num % 2 == 1
	local qstr
	if rem then -- if Q1
		qstr = "q1"
	else        -- if Q2
		qstr = "q2"
	end
	local qs = script.Parent.board.screen.gui.qs
	local q = qs:FindFirstChild(qstr)
	
	if order == 1 then		
		if not q:FindFirstChild(plr.Name) then	
			local foundlabel = q:FindFirstChild(part.Name)
			foundlabel.Name = plr.Name
			foundlabel.Text = plr.Name
		end
	elseif order == 0 then
		local foundplayerlabel = q:FindFirstChild(plr.Name)
		if foundplayerlabel then
			foundplayerlabel.Name = foundplayerlabel.pos.Value
			foundplayerlabel.Text = " "
		end
	end
end

local recentHost
function host(changed)
	if changed ~= "n/a" then
		script.Parent.board.screen.gui.qs.host.Text = "Matchmaking: "..changed
		
		local player = game:GetService("Players"):FindFirstChild(changed)
		if player then
			recentHost = player
			local remoteEvent = game:GetService("ReplicatedStorage"):FindFirstChild("Matchmaking")
			remoteEvent:FireClient(player,"yes")
			local BestBy = game:GetService("ReplicatedStorage"):FindFirstChild("BestBy")
			BestBy:FireClient(player,"yes")
			local JumpingEvt = ReplicatedStorage:FindFirstChild("Jumping")
			JumpingEvt:FireClient(player,"yes")
		end
	else
		script.Parent.board.screen.gui.qs.host.Text = " "
		if recentHost ~= nil then
			local remoteEvent = game:GetService("ReplicatedStorage"):FindFirstChild("Matchmaking")
			remoteEvent:FireClient(recentHost,"no")
			local BestBy = game:GetService("ReplicatedStorage"):FindFirstChild("BestBy")
			BestBy:FireClient(recentHost,"no")
			local JumpingEvt = ReplicatedStorage:FindFirstChild("Jumping")
			JumpingEvt:FireClient(recentHost,"no")
		end
	end
end
local q1plrs = {}
local q2plrs = {}
local q1plrsAlive = {}
local q2plrsAlive = {}

function findPlr(str,q)
	local qfind
	if q == 1 then
		qfind = q1plrsAlive
	elseif q == 2 then
		qfind = q2plrsAlive
	else
		--print("Error: Unknown Q Number!")
	end
	for i,v in pairs(qfind)do
		if str == v then
			return i
		end
	end
end

game.Players.PlayerRemoving:Connect(function(plr)
	local foundPlr = findPlr(plr.Name,1)
	local found2Plr = findPlr(plr.Name,2)
	if foundPlr then
		table.remove(q1plrsAlive,foundPlr)
		checkIfOver()
	elseif found2Plr then
		table.remove(q2plrsAlive,found2Plr)
		checkIfOver()
	else
		--print("none")
	end
end)

function reward(qtabl)
	for i,plr in pairs(qtabl)do
		if game.Players:FindFirstChild(plr.Name) then
			local scoreV = plr:FindFirstChild("leaderstats"):FindFirstChild("Score")
			scoreV.Value = scoreV.Value+1
			--print("Rewarded "..plr.Name)
		end
	end
end

function endRound()
	print("Starting EndRound, q1 = "..#q1plrs)
	for i,plr in ipairs(q1plrs)do
		if plr then
			print("Loading "..plr.Name)
			plr:LoadCharacter()
		end
	end
	for i,plr in ipairs(q2plrs)do
		if plr then
			plr:LoadCharacter()
		end
	end
	wait()
	resetRound()
	wait()
	roundHandler()
	print("Ending EndRound, q1 = "..#q1plrs)
end

function endGame()
	print("game ended")
	Q1Points = 0
	Q2Points = 0
	updateScore()
	hideScore()
	--print(table.concat(q1plrs))
	q1plrsAlive = {}
	q2plrsAlive = {}
	q1plrs = {}
	q2plrs = {}
	print("Tables have been cleared!")
	canStart = true
	ingameButtonEffectDisable()
	currentRound = 1
end

function resetRound()
	print("reseting, q1 = "..#q1plrs)
	q1plrsAlive = q1plrs
	q2plrsAlive = q2plrs
	print("done reseting,q1 = "..#q1plrs)

end

function ingameButtonEffectEnable()
	for i,v in pairs(q1:GetChildren())do
		--print(v)
		v.BrickColor = BrickColor.new("Bright red")
	end
	for i,v in pairs(q2:GetChildren())do
		v.BrickColor = BrickColor.new("Bright red")
	end
end

function ingameButtonEffectDisable()
	for i,v in pairs(q1:GetChildren())do
		v.BrickColor = BrickColor.new("Dark stone grey")
	end
	for i,v in pairs(q2:GetChildren())do
		v.BrickColor = BrickColor.new("Dark stone grey")
	end
end
function updateScore()
	for i,plr in pairs(q1plrs)do
		if plr then
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"set",Q1Points,Q2Points)
		end
	end
	for i,plr in pairs(q2plrs)do
		if plr then
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"set",Q1Points,Q2Points)
		end
	end
end

function showScore()
	--print(q1plrs[1])
	for i,plr in pairs(q1plrs)do
		--print(plr)
		if plr then
			--print("showing score for "..plr.Name)
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"yes",Q1Points,Q2Points)
		end
	end
	for i,plr in pairs(q2plrs)do
		if plr then
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"yes",Q1Points,Q2Points)
		end
	end
end

function hideScore()
	print("Q1plrs: "..table.concat(q1plrs))
	for i,plr in pairs(q1plrs)do
		print(plr)
		if plr then
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"no",Q1Points,Q2Points)
		end
	end
	for i,plr in pairs(q2plrs)do
		if plr then
			local scoreboardevt = ReplicatedStorage:WaitForChild("scoreboard")
			scoreboardevt:FireClient(plr,"no",Q1Points,Q2Points)
		end
	end
	print("finished hiding everyone's score")
end

function rewardTeam(q)
	if q == 1 then
		print("q1 rewarded")
		Q1Points = Q1Points+1
		updateScore()
	elseif q == 2 then
		print("q2 rewarded")
		Q2Points = Q2Points+1
		updateScore()
	end
end

function checkIfOver()
	print("Checking if over")
	print("#q1plrsAlive: "..#q1plrsAlive)
	print("#q1plrs: "..#q1plrs)
	if #q1plrsAlive == 0 then
		print("Q1 Players all eliminated...")
		rewardTeam(2)
		endRound()
	elseif #q2plrsAlive == 0 then
		print("Q2 Players all eliminated...")
		rewardTeam(1)
		endRound()
	else
		endRound()
		--print("Error: Checking over gone wrong!")
	end
end

--Host clicks play--
local WeaponGuiEvt = game:GetService("ReplicatedStorage"):WaitForChild("WeaponGui")

function spawnPlayers(text)
	wait(0.1)
	print("Spawning Players..")
	for i,v in pairs(script.Parent.q1:GetChildren())do	
		local player = game.Players:FindFirstChild(v.plr.Value)
		--print(player)
		if player then
			setupPlayer(player,v,i,text,1)
		else
			disableTransparency(v)
		end
	end
	for i,v in pairs(script.Parent.q2:GetChildren())do
		local player = game.Players:FindFirstChild(v.plr.Value)
--		print(player)
		if player then
			--print("Setting up "..player.." for round")
			setupPlayer(player,v,i,text,2)
		else
			disableTransparency(v)
		end
	end
end

function setupPlayer(player,v,i,text,q)
			print("Setting up"..player.Name)
			local spawnQ = script.Parent:FindFirstChild(v.Parent.Name.."spawn")
			local telepart = spawnQ:FindFirstChild(v.Name)
			player.Character:MoveTo(telepart.Position)
			
			local hum = player.Character:FindFirstChildOfClass("Humanoid")
			
			--Jump Setting--
			if not Jumpable then
				hum.JumpPower = 0
			else
				hum.JumpPower = 50
			end
			----------------
			
			local ForceField = Instance.new("ForceField")
			ForceField.Parent = player.Character
			ForceField.Visible = true
			
			UpdateRoundIntroText:FireClient(player, text,"Normal")
			UpdateRoundIntroText:FireClient(player, text,"EnableTextTransparency")
			
			local PlrWeaponFolder = game:GetService("ReplicatedStorage"):FindFirstChild(player.Name.."'s Weapon Folder")
			local foundPrimary = ReplicatedStorage:FindFirstChild(Type.."_Primaries"):FindFirstChild(PlrWeaponFolder:FindFirstChild(Type.."_Primary").Value)
			if foundPrimary then
				local clonedPrimary = foundPrimary:Clone()
				clonedPrimary.Parent = player.Backpack
				else
				print("Primary not found!")
			end
			
			local foundSecondary = ReplicatedStorage:FindFirstChild(Type.."_Secondaries"):FindFirstChild(PlrWeaponFolder:FindFirstChild(Type.."_Secondary").Value)
			if foundSecondary then
				local clonedSecondary = foundSecondary:Clone()
				clonedSecondary.Parent = player.Backpack
			else
				print("Secondary not found!")
			end
			
			local WalkOrigin = hum.WalkSpeed
			hum.WalkSpeed = 0
			
			--print("index: "..i)
			
			hum.Died:Connect(function()
				if q == 1 then
					print(currentRound)
					print("removing "..player.Name.." from q1plrsAlive")
					print("#q1plrsAlive: "..#q1plrsAlive)
					print("#q1plrs: "..#q1plrs)
					table.remove(q1plrsAlive,i)
					print("#q1plrsAlive: "..#q1plrsAlive)
					print("#q1plrs: "..#q1plrs)
					checkIfOver()
				else
					print("Q: "..q)
					print("removing "..player.Name.." from q2plrsAlive")
					table.remove(q2plrsAlive,i)
					checkIfOver()
				end
				--print("Q1 Players Left: "..table.concat(q2plrsAlive).."  #: "..#q2plrsAlive)
			end)
			player.CharacterAdded:Connect(function(ch)
				if not canStart then
					--print("moving")
					ch:MoveTo(v.Position)
					
					local disableShiftLockEvt = game.ReplicatedStorage:WaitForChild("disableShiftLockEvt")
					disableShiftLockEvt:Fire(player,ch,player.Settings.ShiftLock)
				end
			end)
				
			spawn(function()
			wait(5)
			UpdateRoundIntroText:FireClient(player, "","DisableTextTransparency")
			ForceField:Destroy()
			hum.WalkSpeed = WalkOrigin
			end)
end

local matchmaking = game:GetService("ReplicatedStorage"):FindFirstChild("Matchmaking")


function roundHandler()
	print("Starting Round"..currentRound..", q1 = "..#q1plrs)
	local pointsNeededToWin = (totalRounds/2)+0.5
	--print(pointsNeededToWin)
--	print(Q2Points)
	if Q1Points == pointsNeededToWin then
		wait()
		endGame()
	elseif Q2Points == pointsNeededToWin then
		wait()
		endGame()
	elseif currentRound < totalRounds then
		if currentRound ~= 1 then
			spawnPlayers("Round "..currentRound)
		else
			spawnPlayers("Best By "..totalRounds)
		end
		currentRound = currentRound+1
	end
	--print("q1 = "..#q1plrs)
end

function disableTransparency(part)
	part.Transparency = 1
end

function addPlrs()
	for i,v in pairs(q1:GetChildren())do
		local player = game.Players:FindFirstChild(v.plr.Value)
		if player then		
			table.insert(q1plrsAlive,player)
			table.insert(q1plrs,player)
			print("added "..player.Name.." to q1plrs#: "..#q1plrs)
		end
	end
	for i,v in pairs(q2:GetChildren())do
		local player = game.Players:FindFirstChild(v.plr.Value)
		if player then
			table.insert(q2plrsAlive, player)
			table.insert(q2plrs,player)
			print("added "..player.Name.." to q2plrsAlive#: "..#q2plrsAlive)
		end
	end
	showScore()
end

function onGameStart()
	local GetRounds = game:GetService("ReplicatedStorage"):FindFirstChild("GetRounds")
	totalRounds = GetRounds:InvokeClient(recentHost)
	--print(totalRounds)
	local JumpableEvt = ReplicatedStorage:FindFirstChild("GetJumpSetting")
	Jumpable = JumpableEvt:InvokeClient(recentHost,"State")
	
	addPlrs()
	
	ingameButtonEffectEnable()
	canStart = false
	
	roundHandler()
end

matchmaking.OnServerEvent:Connect(onGameStart)

function withinzone(part, plr)
--	print(plr.Name.." is in zone")
	playerLabel(part, plr, 1)
	part.plr.Value = plr.Name	
	buttonEffect(part)
	if part.pos.Value+1 <= 10 then
		local nextbutton = findnextbutton(part.pos.Value)
		local foo = nextbutton.Transparency
		if plr.Name == "Player1" then
		--	print("button"..nextbutton.Name.." Before Transparency: "..foo)
		end
		nextbutton.Transparency = 0
		if plr.Name == "Player1" then
		--	print("button"..nextbutton.Name.."After Transparency: "..foo)
		end
		nextbutton.enabled.Value = true
	end
end

function notwithinzone(part, plr)
	playerLabel(part, plr, 0)
	if part.name == "1" and plr.Name == "Player1" then
		print("1 is off by "..plr.Name)
	end
	if canStart then
		part.plr.Value = "n/a"
	end
	nobuttonEffect(part)
	if part.pos.Value+1 <= 10 then
		local nextbutton = findnextbutton(part.pos.Value)
		nextbutton.Transparency = 1
		nextbutton.enabled.Value = false
	end
end

function buttonEffect(part)
--	print(part.Name.." changing")
	if canStart == true then
		part.BrickColor = BrickColor.new("Medium stone grey")
		part.Material = Enum.Material.Neon
	end
end

function nobuttonEffect(part)
	if canStart == true then
		part.BrickColor = BrickColor.new("Dark stone grey")
		part.Material = Enum.Material.Plastic
	end
end

function settingup()
	wait(3)
	
	------BUTTON SETUP---------
	local q1parts = q1:GetChildren()
	local q2parts = q2:GetChildren()
	for i,v in ipairs(q1parts)do		
			local val = Instance.new("StringValue")
			val.Parent = v
			val.Name = "plr"
			val.Value = "n/a"
			local bool = Instance.new("BoolValue")
			bool.Parent = v
			bool.Name = "enabled"
			bool.Value = false
			if v.Name == "1" then
				v.Transparency = 0
				bool.Value = true
			end
			buttonTouched(v)
		
	end
	for i,v in ipairs(q2parts)do
		v.Transparency = 1
		local val = Instance.new("StringValue")
		val.Parent = v
		val.Name = "plr"
		val.Value = "n/a"
		local bool = Instance.new("BoolValue")
		bool.Parent = v
		bool.Name = "enabled"
		bool.Value = false
		buttonTouched(v)
	end
	----------------------------
	
	-----SPAWN SETUP------------
	local q1spawns = script.Parent.q1spawn:GetChildren()
	local q2spawns = script.Parent.q2spawn:GetChildren()
	
	for i,v in pairs(q1spawns)do
		v.Transparency = 1
	end
	for i,v in pairs (q2spawns)do
		v.Transparency = 1
	end
	-----------------------------
	
	-----SURFACE GUI SETUP-------
	local surgui = script.Parent.board.screen.gui
	local qs = surgui.qs
	local roundFrame = surgui.round
	local tem = qs.Template
	local incr = -1
	local guiyincr = -0.102
	local incr2 = 0
	local guiyincr2 = -0.102
	for i = 1, 5 do
		local label = tem:Clone()
		label.Visible = true
		label.Name = tostring(incr+2)
		label.Position = UDim2.fromScale(0,guiyincr+0.102)
		guiyincr = guiyincr+0.102
		label.Text = " "
		label.Parent = qs.q1
		local pos = Instance.new("IntValue")
		pos.Name = "pos"
		pos.Value = incr+2
		pos.Parent = label
		incr = incr+2
	end
	for i = 1,5 do 
		local label = tem:Clone()
		label.Visible = true
		label.Name = tostring(incr2+2)
		label.Position = UDim2.fromScale(0,guiyincr2+0.102)
		guiyincr2 = guiyincr2+0.102
		label.Text = " "
		label.Parent = qs.q2
		local pos = Instance.new("IntValue")
		pos.Name = "pos"
		pos.Value = incr2+2
		pos.Parent = label
		incr2 = incr2+2
	end
	-----------------------------
	
end

settingup()
script.Parent.q1:WaitForChild("1"):WaitForChild("plr").Changed:Connect(host)

game:GetService("RunService").Heartbeat:Connect(function()
	print(#q1plrs)
end)

Segment Of Code Where “#q1plrs” returns 0 after “table.remove(q1plrsAlive,i)” :

hum.Died:Connect(function()
				if q == 1 then
					print(currentRound)
					print("removing "..player.Name.." from q1plrsAlive")
					print("#q1plrsAlive: "..#q1plrsAlive)
					print("#q1plrs: "..#q1plrs)
					table.remove(q1plrsAlive,i)
					print("#q1plrsAlive: "..#q1plrsAlive)
					print("#q1plrs: "..#q1plrs)
					checkIfOver()

Code Follow-Through:

Reply if more info is needed!

1 Like

Tables are objects, q1plrsAlive is a reference to q1plrs as on the function resetRound, q1plrsAlive = q1plrs creates q1plrsAlive creates reference to the table instead of copying it thus it actually deleted the value on the q1plrs table as well. This is a normal behaviour. This and this might help.

3 Likes