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

Why isn't every player getting added to the table?

I'm making a round-based game and I'm adding every player to a table to get easy access to them but only one player gets in a table, Can anyone tell me why?

Here's the code to add them to the table


	local playersAlive = {}
	
	for i, player in pairs(game.Players:GetPlayers()) do
		if player then
			table.insert(playersAlive, player)
		end
	end

5 answers

I’m bad at scripting but I think you can try to delete the if loop and see if it works

Can you not do, I haven't tried it but it should work in theory

local playersAlive = game.Players:GetPlayers()

1 comment

0

that's a variable, not a table

What I would do is to put the for loop inside a while true loop, here's what I think will work

local playersAlive = {}	 

while true do
	wait()
	for i, player in pairs(game.Players:GetPlayers()) do
		    if player then
		        table.insert(playersAlive, player)
		end
	end
end

--btw i prob would recommend you do local playersAlive = game.Players:GetChildren() since this would just be easier instead of doing this loop

1 comment

0

Didn't work

This should be working. You weren't supplying all the parameters necessary for table.insert

local playersAlive = {}

for i, player in pairs(game.Players:GetPlayers()) do
    if player then
        table.insert(playersAlive,#playersAlive+1, player)
    end
end

The second parameter is where you put the thing within the table. This will automatically set the index to the tables length +1

By the way you don't need to include the if statement, it's just useless in this case.

Plus I'd personally use collection service Instead of manually adding and removing players from the players alive table, but it doesnt matter, it's just my preference

1 comment

0

Didn't work

prints playersAlive table, updates every 10 seconds

local Players = game:GetService("Players")
local playersAlive = {}

local function onPlayerAddToTable(player)
	table.insert(playersAlive, "User: " .. player.Name)
	print("worked")
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAddToTable(player)
end
Players.PlayerAdded:Connect(onPlayerAddToTable)

while true do
	wait(10)
	print(playersAlive)
end

--dont care if the code output is messy it works ok bye
--by piximentility

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