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

How to make a function that grabs every players name and put them in an array?

Asked by 1 year ago
Edited 1 year ago

I have this code that I've been trying to work on but can't seem to get to work correctly

Array = {}
local players = game.Players:GetPlayers()

function getPlayers() 
    for _,v in ipairs(game.Players:GetPlayers()) do
        table.insert(Array,v.Name);
    end
end

3 answers

Log in to vote
2
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
1 year ago
local function getAllPlayerNames()
    local result = players:GetPlayers()

    for index, player in players do
        result[index] = player.Name
    end

    return result
end
Ad
Log in to vote
0
Answered by
Opieky 0
1 year ago
Edited 1 year ago

Use the GetChildren or GetPlayers() method to create a table of the given instance's children. For your case:

local players = game.Players:GetChildren() --GetPlayers() will work as well

From here, if you want to turn this array from an array of player objects to an array of player names (strings) you could map over each value using the following function:

--mutates every field of t using f
local function map(t, f)
    --create the return table
    local nt = {}
    --loop through every field
    for i = 1, #t do
        --assign each field of nt to the 'updated' value provided by f
        nt[i] = f(t[i])
    end
    return nt
end

And your final result would be:

local playerNames = map(game.Players:GetChildren(), function(field)
    return field.Name
end)

You could also just individually access a players name when needed like players[i].Name.

1
That's a bit extra, don't you think? And please use more descriptive variables Ziffixture 6913 — 1y
Log in to vote
0
Answered by
Xapelize 2658 Moderation Voter Community Moderator
1 year ago

The only mistake you are making is you aren't clearing the old values in the Array when you need to update the Array.

That will make the Array look like this if you call the getPlayers function twice:

{ "tykoon3", "tykoon3" }

Corrected script:

Array = {}
local players = game.Players:GetPlayers()

function getPlayers() 
    table.clear(Array)
    for _,v in ipairs(game.Players:GetPlayers()) do
        table.insert(Array,v.Name);
    end
end

Answer this question