Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to check if the value is already in table?

I have a script where it adds the name of player when it touches the part, but right now it keeps on adding multiple times(every bodypart that touches), and when i touch again it adds additional same person. To prevent that, i want to make a function where it checks if the value already exists so it wont spam the username in table.

Ex.

 myTable = {}

local part = script.Parent

part.Touched:Connect(function(registeredTeleport)
	if registeredTeleport.Parent:FindFirstChild("Humanoid") then
		if registeredTeleport.Parent.Name --[already exists--] then
			table.remove(myTable,registeredTeleport.Parent.Name(the one inside table))
		elseif registeredTeleport.Parent.Name ~= --[already exist--] then
			table.insert(myTable,registeredTeleport.Parent.Name)
		end
	end
end)


wait(10)
table.sort(myTable)

repeat 
	local temporaryName = myTable[1]:FindFindFirstChild("Head")
	if temporaryName == ~~~~"Head" and temporaryName:FindFirstAncestorOfClass("Model") then
		temporaryName.Cframe = Cframe.new(X,Y,Z)	
	end	
	table.remove(myTable,[1]
until
	#myTable == 0
end

1 answer

✓ Accepted answer

There is two ways I can think of.

1. Linear Search

A linear search is a searching algorithm that searches for an element in a list.

local function tableContains(tbl, element)
	for _, v in ipairs(tbl) do
		if (rawequal(v, element)) then
			return true;
		end
	end
	return false;
end

This function returns true if the table contains element, checking each element in tbl one by one.

2. Dictionaries

Table have an array part and a dictionary part. The dictionary part is an unordered mapping of keys to values.

It looks more or so like this:

{
	key = "value",
	key2 = "value2"
	-- and so on
}

So you can use the name of the player as the key, and use true as the value, just to show that they are in the table. Also duplicates will not be an issue.

myTable[player.Name] = true

1 comment

0

the dictionary way worked out. Thank you for help :D

This discussion is preserved as it was. New answers, comments, and votes are closed.