Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
MattVSNNL 620 Moderation Voter
4 years ago

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

1local playersAlive = {}
2 
3for i, player in pairs(game.Players:GetPlayers()) do
4    if player then
5        table.insert(playersAlive, player)
6    end
7end

5 answers

Log in to vote
0
Answered by
7777ert 49
4 years ago

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

Ad
Log in to vote
0
Answered by 4 years ago

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

1local playersAlive = game.Players:GetPlayers()
0
that's a variable, not a table piximentility 37 — 4y
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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

01local playersAlive = {} 
02 
03while true do
04    wait()
05    for i, player in pairs(game.Players:GetPlayers()) do
06            if player then
07                table.insert(playersAlive, player)
08        end
09    end
10end
11 
12--btw i prob would recommend you do local playersAlive = game.Players:GetChildren() since this would just be easier instead of doing this loop
0
Didn't work MattVSNNL 620 — 4y
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

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

1local playersAlive = {}
2 
3for i, player in pairs(game.Players:GetPlayers()) do
4    if player then
5        table.insert(playersAlive,#playersAlive+1, player)
6    end
7end

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

0
Didn't work MattVSNNL 620 — 4y
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

prints playersAlive table, updates every 10 seconds

01local Players = game:GetService("Players")
02local playersAlive = {}
03 
04local function onPlayerAddToTable(player)
05    table.insert(playersAlive, "User: " .. player.Name)
06    print("worked")
07end
08 
09for _, player in pairs(Players:GetPlayers()) do
10    onPlayerAddToTable(player)
11end
12Players.PlayerAdded:Connect(onPlayerAddToTable)
13 
14while true do
15    wait(10)
16    print(playersAlive)
17end
18 
19--dont care if the code output is messy it works ok bye
20--by piximentility

Answer this question