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

Help making a playerlist table?

Asked by 7 years ago
Edited 7 years ago

So I'm trying to apply/test my beginner knowledge and I appear to have gotten stuck. What I'm trying to explore is the game.Players:GetPlayers() method/function.

I'm guessing that if I call that function after a player is leaving, it will return a table without the player that left? I'm assuming I'm wrong because it doesn't seem to be working. If that's the case, then I'd like some help on how to do exactly that.

Furthermore, an error prompts when the PlayerRemoving event is called, simply saying "An error has occurred" and doesn't print the table.

playerservice = game:GetService("Players")

function print_table(tab) -- I want to print out what's in the table
    for i,v in ipairs(tab) do
        local val = tostring(v)
        print("i = "..i.." v= "..val)
    end
end

playerservice.PlayerAdded:connect(function(plr)
    print_table(playerservice:GetPlayers())
end)
playerservice.PlayerRemoving:connect(function(plr)
    print_table(playerservice:GetPlayers())
end)

1 answer

Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

I'm not sure if your way would work or if there was a way to make it work, but what I do is this. Idk why really you are using a service called "Players" being as you could just do game.Players to access it.

plr = {} -- The table for the players 
p = game.Players:GetPlayers() -- This is basically just used so you can get a list of all of the players

for i = 1,#p do
    table.insert(plr, p[i]) -- Takes the list of all people and inserts them into the table called "plr"
end

function getNumber(obj) -- this function will be used to get who left
    for i = 1,#plr do -- go through all the players 
        if plr[i]==obj then -- if the person in the list is the one you are looking for
            return i -- return that certain person
        end
    end
end

game.Players.ChildAdded:connect(function(NewPlayer) 
    table.insert(plr, NewPlayer) -- adds players to the list when they join
end)


game.Players.ChildRemoved:connect(function(WhoLeft) 
    table.remove(plr, getNumber(WhoLeft)) -- notice I call the getNumber function for the person who left
end)

Then you could use the list of players for different things such as making custom player lists, which I actually used this for.

If this helped please remember to mark it as answered, if not then please message me or comment so I can know what I could do better for you!

0
Ah, many thanks! Thank you for explaining it. SketchTitan 40 — 7y
0
No problem mate. Happy scripting! RockerCaleb1234 282 — 7y
Ad

Answer this question