Trying to make a script that checks if a player is already in the table when they touch a object, if they are in the table then it should just do nothing, if they aren’t then it should add them to the table. Once a second player touches the part they keep getting added whenever they touch it.
part = script.Parent
mytable = {}
script.Parent.Touched:Connect(function(hit)
local hum = hit.Parent:FindFirstChild("Humanoid")
if hum then
local player = game:GetService("Players"):GetPlayerFromCharacter(hit.Parent)
if player then
local iterations = 0
for i,v in pairs (mytable) do
iterations = iterations + 1
end
if iterations == 0 then
table.insert(mytable,player)
print("theres no one in the table so just add the player")
end
local intable = false
for i,v in pairs(mytable) do
if v == player then
intable = true
---if player is in then make intable true
print(intable)
end
end
for i,v in pairs (mytable) do
if intable == false then
print()
print("adding"..player.Name.."to the table")
table.insert(mytable,player)
end
end
end
end
end)
If you basically want to add a player to a table, when a part is touched,you could do this
(unless you will be saving the data, in which case you should use user ids instead)
Tested
it works, if a player is in the table then it prints “in the table” else it adds every player who touches it, but remember the table won’t save without Data Stores !
local players = game:GetService("Players")
local debounce = false
player_table = {}
script.Parent.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character~= nil then
if character and debounce then
debounce=true
local player = character.Parent
if not table.find(player_table,player)
then table.insert(player_table,player)
return print("inserted" .. player.Name .. "to the table !")
end
--If he is already in the table, then this will happen
print(player.Name.." is already in the table, not adding him")
wait(1)--debounce cooldown
debounce=false--don't want this to fire 17 times !
end
end
end)
Dictionaries are great for things like this because you can index a player by name without fear of duplicates. If the key associated with their name exists, then you can ensure that they’ve already been added to the table.
local Players = game:GetService("Players")
local Touched = {}
script.Parent.Touched:Connect(function(Hit)
local Humanoid = Hit.Parent:FindFirstChildOfClass("Humanoid")
if Humanoid and Humanoid.Health ~= 0 then
local Player = Players:GetPlayerFromCharacter(Hit.Parent)
if not Touched[Player.Name] then
print("Adding " .. Player.Name .. " to the table")
Touched[Player.Name] = Player
end
end
end)