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)
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)
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)
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
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)