Why does this result as nil?

Pretty much I’m wanting to find the players name that is randomly selected in this table. The value is found but it always come back as nil which is confusing me. Any help would be much appreciated

local function Game()
	local randomplayer = math.random(1, #playersTable)
	local player = table.find(playersTable, randomplayer)
	print(player)
end

while true do 
	task.wait(1)
	if table.maxn(playersTable) >= 2 then 
		Game()
	end
end

Also anybody know how I can tidy this while true do loop to only play when a value is added or removed from the playersTable?

Where do you define playersTable in the code?

1 Like

I define it at the top as a part of my variables

local playersTable = {}

But it has 2 values in the table at the point where the code will start running as u can see by this

if table.maxn(playersTable) >= 2 then 

The players get added into the table when they join the game and removed when they leave.

I am also using an Array not a dictionary

Is there a reason you’re using table.maxn rather than just #playersTable ? Also, the issue will have to do with the playersTable, so can you show all the code related to it please.

local Players = game:GetService("Players")

local playersTable = {}

game.Players.PlayerAdded:Connect(function(player)
	table.insert(playersTable, player.Name)
	player.CharacterAdded:Connect(function(character)
		task.wait()
		character:FindFirstChild("HumanoidRootPart").CFrame = game.Workspace.Spectators.CFrame
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	table.remove(playersTable, table.find(playersTable, player.Name))
end)

local function Game()
	local randomplayer = math.random(1, #playersTable)
	local player = table.find(playersTable, randomplayer)
	print(player)
end

while true do 
	task.wait(1)
	if table.maxn(playersTable) >= 2 then 
		Game()
	end
end

When I define the players its fine because if I print the playerstable content i get the full list of players and

not really I was just experimenting with what functions table had but it does the same thing

table.find searches for a value within a table and returns the index it is currently at. You are providing this function with an index, and trying to find it. So, if the game randomly selects player 2, the code table.find(playersTable, 2) would return nil because there is no value “2” within the table. You can fix it by doing something like such:

local playerName = playersTable[randomplayer]

1 Like

thanks bro that helped so much!

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