How to detect if a value already exists in a table before inserting?

I was trying to make an “ignore list” for a gun system using the FastCast module. FastCast has a blacklist function that makes its rayscasts ignore everything in a table.

I tried making a system where accessories will be detected whenever a player spawns and respawns.
The issue with this is that if a player dies and respawns with the same hats on, it will add the same accessories again and again.

I just started trying to learn scripting a week ago, so I’m not sure if having a large table will have a large performance impact, but apparently this is a memory leak?

I tried adding a checkDupe() function that would check if “v” is equal to any value in the “rayIgnoreList” table before adding it to the table, but the for loop (the one that checks if v has a duplicate) doesn’t run:

local rayIgnoreList = require(game:GetService("ReplicatedStorage"):WaitForChild("IgnoreList"))
local Players = game:GetService("Players")

local function checkDupe(v)
	for i, hat in ipairs(rayIgnoreList)do
		if v == hat then
			print("Duplicate Accessory Detected: ", v)
			return false
		else
			return true
		end	
	end
end

game.Players.PlayerAdded:connect(function(plr)
	print("Player Detected:", plr)
	plr.CharacterAdded:Connect(function(character)
		print("Character Detected")
		plr.CharacterAppearanceLoaded:Connect(function(character)
			print("Character Fully Loaded")
			local humanoid = character:WaitForChild("Humanoid")
			if humanoid then
				print("Humanoid Detected")
				if plr.CharacterAppearanceLoaded then
					print("Appearance Loaded")
					for i, v in ipairs(humanoid:GetAccessories()) do
						print("Accessories Detected")
						if checkDupe(v) then									
							table.insert(rayIgnoreList, v)
							print("Inserted: ", v)	
						end
					end
				end
			end
		
		end)
			
	end)
end)
1 Like

Well, it really depends if the table has instances or it has strings that represent accessories. If it’s instances then use v, if it’s strings then use v.Name. I do like the method of a loop, but roblox has a table.find() function that is useful.

if table.find(table , value, index) then -- index is optional
2 Likes

This is not tested.

function checkDupe(table,item)
   for i,v in pairs(Table) do
       if v.Name == item.Name then
           print("Duplicate Accessory Detected: "..v.Name)
           return false
       else
           return true
       end
   end
end