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

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

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

local function getAllPlayerNames()
	local result = players:GetPlayers()

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

	return result
end

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 comment

1

That's a bit extra, don't you think? And please use more descriptive variables

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

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