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
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: