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

Why do players keep getting added in the list?

first_map_voter = workspace.voter.first_map
voters_for_first = {}

first_map_voter.Touched:Connect(function(object)
	if not voters_for_first[object.Parent] then
		table.insert(voters_for_first, object.Parent)
		print(voters_for_first)
	end
end)

So this code should add every player who touches a part in a list but only once. if i run it and step on the part, i keep getting added everytime I move, even if I'm already in the list.

ignore the sh#tty names

1 answer

indexing indexes a key in table, for example

local Table = {
	["Key"] = 5,
}

Table["Key"] -- 5

table.insert inserts given element at the last slot of an array, it functions similarly (don't take third argument in count) to this

function table.insert(Table, Element)
	Table[#Table + 1] = Element
end

You see it inserts it with number index, so you could index it with number like

Table[1] -- Element

However it's not possible in your case so all you do is use "table.find" which returns index of element inside of a table with given value, it returns nil if it's not found so for your case it's the best

first_map_voter = workspace.voter.first_map
voters_for_first = {}

first_map_voter.Touched:Connect(function(object)
	if not table.find(voters_for_first, object.Parent) then
		table.insert(voters_for_first, object.Parent)
		print(voters_for_first)
	end
end)

I recommend you checking if the object that touched the part has humanoid because from what i can see it's map picker, you would want only humans to be able to vote.

You also should be using local before variables unless you work with the enviroment. It saves you some performance because with globals the compiler has to also call function "GETGLOBAL" which hurts nanoseconds of performance.

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