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


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

5 answers

Log in to vote
0
Answered by
7777ert 49
3 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 3 years ago

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

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

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
0
Didn't work MattVSNNL 620 — 3y
Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

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

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

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

Answer this question