Check total entities and entity spawntime

I’m currently working on a script, and it spawns a certain weapon after a NPC is killed:



local WEAPONDROPS= { --100%
	"weapon_ar2",
	"weapon_smg1",
	"weapon_shotgun"
}
hook.Add("OnNPCKilled", "DropWeaponOnNPCKilled", function(npc, killer)
	local randomitem = nil
	chance = math.random(1,89)
	if chance > 0 && chance <= 89 then randomitem = table.Random(WEAPONDROPS) end
	item = ents.Create(randomitem)
	item:SetOwner(World)
	item:SetPos(npc:LocalToWorld(npc:OBBCenter()))
	item:Spawn()
end)


What I need to be able to do is check the max amount of those entities spawned, and if it’s over 7 then it doesn’t spawn any more. I also need to create spawntime for the entity created. After a certain amount of seconds the entity is destroyed, to make room for more. I’ve tried to use



for k, ent in pairs (ents.GetAll()) do
	if ent:IsValid() then
		if (ent:GetClass() == "weapon_ar2" or ent:GetClass() == "weapon_smg1" or ent:GetClass() == "weapon_shotgun") > 7 then return end
		end
	end
end


to check the entities, but it gives me this error: “attempt to compare number with boolean”.


if #ents.FindByClass("weapon_ar2") + #ents.FindByClass("weapon_smg1") + #ents.FindByClass("weapon_shotgun") > 7 then end

Like that?

That worked, thanks. I just need a spawntime for the entities now.

What do you mean by spawntime? Like, delay the entity from spawning?

[lua]
SafeRemoveEntityDelayed( ent, 10 )
[/lua]

That will remove an entity after 10 seconds

I mean something that will destroy the entity after a certain amount of seconds of it being spawned. In example: after I would kill a NPC and it would drop a AR2. After 20 seconds of it not being picked up, it gets destroyed.

Edit:
I tried making this on my own, but mine has one flaw: it doesn’t delete the entity 20 seconds after it was spawned. It just deletes all entities in “EntityDelete” every 20 seconds. An example of this being a problem, is if I just killed a NPC and it dropped a weapon, the counter could be at 19 seconds and it would delete the weapon before I could have a chance to pick it up.



NextCheck = 0
function DeleteWeapons()
	if CurTime() >= NextCheck then
		local EntityDelete = ents.FindByClass("weapon_shotgun")
		EntityDelete = table.Add(EntityDelete, ents.FindByClass("weapon_shotgun"))
		EntityDelete = table.Add(EntityDelete, ents.FindByClass("weapon_smg1"))
		EntityDelete = table.Add(EntityDelete, ents.FindByClass("weapon_ar2"))
		for _, ent in pairs(EntityDelete) do
			ent:Remove()
		end
		NextCheck = CurTime() + 20
	end
end
hook.Add("Think", "DeleteWeps", DeleteWeapons)