Table.find not working?

hi, i have a table of the players in the game, and i’m trying to get the current player from that table, but table.find returns nil

game.Players.PlayerAdded:Connect(function(player)
	local players = {
		player1 = game.Players:GetPlayers()[1];
		--player2 == game.Players:GetPlayers()[2]
	}
	
	local function endTurn()
		print(table.find(players, player))
		print(player, player.Name, player.Parent)
		print(players.player1, players.player1.Name, players.player1.Parent)
	end

image
as you can see, player and player1 are the same thing, but it returns nil

1 Like

i believe table.find() returns numerical indexes
so if you tried to find something that doesn’t have a number for the index (“player1” = Drixitty) it would return nil not “player1”

local Fruit = {
  ["Fruit1"] = "Apple";
  ["Fruit2"] = "Banana";
}
print(table.find(Fruit, "Apple")) --> nil
local Fruit = {
  [1] = "Apple";
  [2] = "Banana";
}
print(table.find(Fruit, "Apple")) --> 1
1 Like

yeah that makes sense and that was the issue, but how should i go about doing this then? i’m trying to get the current player and then go to the next player in the table, i’m trying to make turns

You might want to use for loop, loop through all values inside the table and if the value of one of them (which is the player) is equal to the player variable which we already had from PlayerAdded event, we set the foundPlr to the key so you can use it later.

local foundPlr
local function endTurn()
	for key, value in players do 
		if value == player then 
			foundPlr = key 
			break 
		end 
	end
end

basically, the key is the name of the value inside the table, and value is the value of the name that is inside the table too.

local players = {
		player1 = game.Players:GetPlayers()[1];
		--player2 == game.Players:GetPlayers()[2]
	}

According to this table, key will be equal player1 and value will be game.Players:GetPlayers()[1];

well you could just turn the Players dictionary into an array since Player1 is the same as index 1

(i thought this was the obvious solution)

local PlayersInGame = {
  ["Player1"] = game.Players:GetPlayers()[1],
  [1] = game.Players:GetPlayers()[1]
}
print(table.find(PlayersInGame, Player)) --> 1
print(Player, Player.Name, Player.Parent) --> Drixitty Drixitty Players
print(PlayersInGame[1], PlayersInGame[1].Name, PlayersInGame[1].Parent) --> Drixitty Drixitty Players

Create a new function.

function table.Find(Table,index)
assert(Table)
Count=0
for i,v in pairs(Table) do Count+=1;end
for i,v in next,Table do
if i==index then
return rawget(Table,i)
elseif i==#Count and i~=index then
return nil
end
end
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.