[SOLVED] Is there a way to remove everything from a table once nothing is in a folder?

I have made a tower control script that works in a part in the workspace. I would like to know if there is a way to remove everything from the table when the enemies folder is emptied. Basically, the script attacks the first enemy that enters its radius (magnitude), then the second, third, etc. Here is the script:

local RunService = game:GetService('RunService') --Get RunService

local enemies = {} --Create table

local oldCFrame --Variable for later

local highestVal = 0 --Set highestVal

local attack = false --Debounce

workspace:WaitForChild('Maps'):WaitForChild('Tutorial'):WaitForChild('Enemies').ChildAdded:Connect(function(enemy) --Get when new enemy added
	table.insert(enemies, enemy) --Add enemy to table
	oldCFrame = enemy.HumanoidRootPart.CFrame --Set oldCFrame
end)

RunService.Heartbeat:Connect(function()
	for i, enemy in ipairs(enemies) do --Iterate table of enemies
		if enemy:FindFirstChild('HumanoidRootPart') then --Check enemy not dead
			local magnitude = (script.Parent.Position - enemy.HumanoidRootPart.Position).Magnitude --Get magnitude of enemy away from tower
			if magnitude < 25 then --Check if enemy not to far away
				local newCFrame = enemy.HumanoidRootPart.CFrame --Get CFrame of enemy
				if newCFrame ~= oldCFrame then --Check if enemy moved		
					oldCFrame = newCFrame --Set oldCFrame to newCFrame
					enemy.TimeInDistance.Value += 1 --Add 1 to value for finding correct enemy to target
					local distanceVal = enemy.TimeInDistance.Value --Set distanceVal
					if distanceVal > highestVal then --Check if distanceVal greater than highestVal, else nothing changes
						highestVal = distanceVal --Set new highestVal
						if enemy:FindFirstChild('Humanoid') then --Another check if enemy died
							if attack == false then
								attack = true --Set to attacking
								enemy.Humanoid.Health -= 1 --Take away health
								task.wait(1) --Wait
								
								--Remove from table if nothing in folder????????  (Also I would reset highestVal)
								
								attack = false --Set so tower can attack again
							end
						end
					end
				end
			end
		end
	end
end)

Thank you for the help in advance!

1 Like
local tab: {any} = {}
local folder: Folder

if #folder:GetChildren() == 0 then
    table.clear(tab)
end

I completely forgot about table.clear! This works perfectly, thank you so much.

folder.ChildRemoved:Connect(function()
	if #folder:GetChildren() == 0 then
		table.clear(enemies)
		highestVal = 0
	end
end)
1 Like