Doesn't check if the player is included in a table

I’m attempting for this to print “yes” if they player’s username has been provided in the table, but it doesn’t seem to function and operate as it. What’s the concurrent issue here? Here’s the code:

local whitelisted = {"Doqee", "bigbrain"}
	for i = 1, #whitelisted do
		if plr.Name == i then 
		print("yes")
	end
end

Simple, just put an “else” :

local whitelisted = {"Doqee", "bigbrain"}
for i = 1, #whitelisted do
	if plr.Name == i then 
		print("yes")
	else
		print("no")
	end
end

The table library has a function for this already.

local whitelisted = {"Doqee", "bigbrain"}
if (table.find(whitelisted, plr.Name) ~= nil) then
	print("yes")
else
	print("no")
end
local whitelisted = {"Doqee", "bigbrain",}
if table.find(whitelisted,plr.Name) then
-- passed
else
-- not passed
end

Looping isn’t needed as there is a function for the table to find values. This is much more efficient than looping.

Please do not you can’t use table.find on dictionary, it only works on arrays.

2 Likes

You could do:

local whitelisted = {"Doqee", "bigbrain"}
game.Players.PlayerAdded:Connect(function(plr)
for i, v in pairs(whitelisted) do -- Loops through the table
if plr.Name == v then -- Checking to see if the player is in the table
print("Yes")
else
print("No")
end
end
end)

table.find isn’t necessarily more efficient than a loop, it basically does the same thing except that it is included as a built-in function of the table library.

It is essentially equivalent to something like this:

function linearSearch(array, value, startIndex)
	startIndex = startIndex or 1
	for i = startIndex, #array do
		if (array[i] == value) then
			return i
		end
	end
	return nil
end

table.find is all that is needed for OP’s use case, though depending on how you are structuring your data it could eventually be useful to use your own methods for table operations (for example, a binary search on a sorted array runs in logarithmic time instead of linear time if you used a linear search.)

Thank you all for the replies! It seems like they’re often a solution, but I’d prefer Quwan’s as it’s simple to acknowledge within to understand. I appreciate your participation.