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

Any way to get things in a table without using an iv loop?

What I want is

lets say we have a table of players

Players:GetPlayers() -- Table

if I wanted to get a players character i'd have to do an for i,v loop on the getplayers table

Is there any way to get their character without doing v.Character

Something simple and efficient like unpack?

Also don't tell me something like

Players:GetPlayers()[Name]

Im looking for a way to get every character without doing an iv loop

1 answer

There is no point in doing that, just use ipairs loop. If friend suggested you a challenge then fine, you can use normal for loop like this:

local Players = game:GetService("Players")

local function get_characters()
	local clients = Players:GetPlayers()
	local characters = {}
	
	for index = 1, #clients do
		local client = clients[index]

		if client then
			table.insert(characters, client.Character)
		end
	end

	return characters
end

If that is also restricted to you, use the deprecated foreach / foreachi (Difference between them is same as between pairs and ipairs, the one with "i" goes by order and breaks the loop if hits a nil value) loop which runs function for each element in a table:

local Players = game:GetService("Players")

local function get_characters()
	local clients = Players:GetPlayers()
	local characters = {}
	
	local function _add_character(index, client)
		if client then
			table.insert(characters, client.Character)
		end
	end

	table.foreachi(clients, _add_character)

	return characters
end

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