How to remove player from table when leaving region3?

So I want to remove the player from the table when he leaves the region3
But everywhere I tried to put “removeTable(game.Players.LocalPlayer)” to remove it either didn’t run it or it ran it while the player is in the area
Any help?

local Areas = game.Workspace:WaitForChild("Areas")
local Found=false
local label = game.Players.LocalPlayer.PlayerGui.AreaGui.TextLabel
local tweenservice = game:GetService("TweenService")
local players = {}
function foundInList(player)
	for _,target in ipairs(players) do
		if target == player then
			return true;
		end
	end
	return false;
end
local function removeTable(plr)
	table.remove(players,players[plr])
end
while wait(1)do
	for i,v in pairs(Areas:GetChildren())do
		Found = false
		local region=Region3.new(v.Position-(v.Size/2),v.Position+(v.Size/2))
		local parts = game.Workspace:FindPartsInRegion3WithWhiteList(region,game.Players.LocalPlayer.Character:GetDescendants())
	
for _, part in pairs(parts)do 


if part:FindFirstAncestor(game.Players.LocalPlayer.Name)then

print("Player was found")

Found = true
break
else
	Found = false
			print("Player was not found in region")
				
	end
		end
		if Found == true then
			if not foundInList(game.Players.LocalPlayer) then

				print("Adding "..game.Players.LocalPlayer.Name)
				table.insert(players,game.Players.LocalPlayer)
				print(players)
			game.Players.LocalPlayer.PlayerGui.AreaGui.TextLabel.Text = "["..v.Name.."]"
			tweenservice:Create(label,TweenInfo.new(0.5),{TextTransparency = 0}):Play()
			wait(3)
			tweenservice:Create(label,TweenInfo.new(0.5),{TextTransparency = 1}):Play()
			wait(1)
				game.Players.LocalPlayer.PlayerGui.AreaGui.TextLabel.Text = "[Somewhere]"
				
				break
				
			end
			

			

					
					
				end
			end
			
		end
		
	





table.remove takes an index to remove

table.remove(players, table.find(players, plr))

Be careful of this because if the index returned by table.find is nil it will remove the last index instead. Something like this is more favorable:

local plrIndex = table.find(players, plr)

if plrIndex then
    table.remove(players, plrIndex)
end
1 Like