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

Problems with a table and looping. How can I fix this?

Hello, great community.

The script that I'm wanting to make is simply that I choose some friends to get some powers on my game when they join. But it seems that Roblox doesn't recognize the table and doesn't fire the loop to my friends. I don't get anything on the output, it just doesn't do anything.

Friends = {"Roblox";"MasterRoblox43";"silversiverbas"}

game.Players.PlayerAdded:Connect(function(a)
	print("Checking "..a.Name) -- It only prints.
			for i,v in pairs (game.Players:GetChildren()) do
				if v.Name == Friends then
				for i = 1,3 do
				
				-- Code of the powers

			end
		end
	end
end)

What am I doing wrong, I think it's the table or the if v.Name == Friends then I'm not sure, if you know the issue, please let me know.

In the output, it only prints the print("Checking "..a.Name) but when my friends join it just say "check Friend name" and don't fire the loop that how it's supposed to be.

2 answers

✓ Accepted answer

You've just got the application of the for loop mixed up. What you're currently doing is checking if each player in Players's name is equal to a table (which will always return false) instead of checking if the player's name is within the table.

You can switch the parameters of the for loop as follows:

Friends = {"Roblox";"MasterRoblox43";"zoogizile";"silversiverbas";"zoogizile"}

game.Players.PlayerAdded:Connect(function(a)
	print("Checking "..a.Name) -- It only prints.
	for i, v in pairs(Friends) do
		print(v) --[[ will print:
			Roblox
			MasterRoblox43
			zoogizile
			...
		]]
		if a.Name == v then -- check if the player that joined is equal to one of the names in Friends
			-- give powers
			break -- stop the loop here so it doesn't keep computing after we've found the right player
		end
	end
end)

Please accept this answer if it helps! Thanks!

1 comment

0

Thanks for the nice quality of the answer, really helped me alot, thanks man!

Building off of what HollowMariofan said:

You can simplify your script by transforming your list into a dictionary for fast lookup:

local friends = {"Roblox", "MasterRoblox43", "etc"}
for i = 1, #friends do
	friends[friends[i]] = true
end
game.Players.PlayerAdded:Connect(function(player)
	if friends[player.Name] then
		-- give powers
	end
end)

If this syntax is unfamiliar to you, read through http://lua-users.org/wiki/TablesTutorial

1 comment

0

I will check how syntax work, thanks for sharing the link.

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