How Would I Check if a Player is Already in a Table

What is The Best way To Find something in a Table? I’ve Tried Multiple Times to Do this But I can’t Figure it out.

local newTable = {}

local function Touched(hit)
       local player = game.Players:GetPlayerFromCharacter(hit.Parent)
       for i = 1,#newTable do
           if  newTable[i] == player.Name then
            end
      end
end


script.Parent.Touched:Connect(Touched)
1 Like

The best way would be to make a dictionary, which stores keys instead of numerical indexes, but points to a value the same way as numerical indexes.

Here’s an example:

local newTable = {}

local function Touched(hit)
       local player = game.Players:GetPlayerFromCharacter(hit.Parent)
        if player and newTable[player] then
          --//Player instance is a key in the table
      end
      end
end)


script.Parent.Touched:Connect(Touched)

To add a player into the dictionary, you can do:

newTable[player] = true

Hope this helps :slight_smile:

5 Likes
local newTable = {}

local function Touched(hit)
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	for k, v in pairs(newTable) do
		if not newTable[player] then
			newTable[player] = true
		print("Added to Table")
elseif newTable[player] then
			print("Already in Table")
		end
	end
end


script.Parent.Touched:Connect(Touched) 

I ran This, But It Didn’t Print anything.

Here’s an example from a project I’m working on at the moment:

local PlayersInClassHub = {} -- table where players interacting with the hub 

Remotes.GetClassDescription.OnServerInvoke = function(Player, RequestedClass)
    if PlayersInClassHub[Player.Name] then -- check if the player is in the hub
        if ClassSettings["Classes"][tostring(RequestedClass)] then
            return ClassSettings["Classes"][tostring(RequestedClass)]
        else
            warn("Warning | " .. Player.Name .. " requested an invalid class." .. " (" .. RequestedClass .. ")")
            return nil
        end
    else if PlayersInClassHub[Player] == nil then
            Player:Kick("illegal request") -- exploiter most likely fired the remote while not being physically at the class hub
        end
    end
end
1 Like

Just use Table.Find(newTable,Player.Name)

and put it through an if statement:

if Table.Find(newTable,Player.Name) then

     print(Player.Name.."Is inside the table!")

end
3 Likes

You should try taking out the for loop, it’s unneeded when using a dictionary in this way:

local newTable = {}

local function Touched(hit)
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player and not newTable[player] then
		newTable[player] = true
		print("Added to Table")
	elseif newTable[player] then
		print("Already in Table")
	end
end


script.Parent.Touched:Connect(Touched) 
3 Likes

This Worked! Thank you So Much!

1 Like