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