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

How to loop through Instances?

I am making some basic admin commands, but I am having some trouble. I often use a 'for' loop, but when I attempt to use it to loop through something like 'game.Players', I get the following error: 'table expected, got Instance'.

Here's the script I am using:

local Admins = {
	"SirGamezy"
}

local Cmds = {
	"reset"
}

game.Players.PlayerAdded:Connect(function(plr)
	p.Chatted:Connect(function(msg)
		for i,v in pairs(Admins) do -- This loop works
			if v == plr.Name then
				local split_string = string.split(msg," ")
				local firedCmd = split_string[2]
				if firedCmd == "reset" then
					local target = split_string[3]
					if target == "all" then
						for i,v in pairs(game.Players)  do -- This loop doesn't work
							v.Character.Humanoid.Health = 0
						end
					
					elseif target == "others" then
						for i,v in pairs(game.Players) do -- This loop doesn't work
							if v ~= plr.Name then
								v.Humanoid.Health = 0
							end
						end
					
					else
						for i,v in pairs(game.Players) do -- This loop doesn't work
							if v == target then
								v.Humanoid.Health = 0
							end
						end
					end
				end
			end
		end
	end)
end)

Any help on this matter would be greatly appreciated!

1 answer

✓ Accepted answer

You cant loop through instances, you loop through tables and you get a table of players using game.Players:GetPlayers()

example

local players = game:GetService("Players")

for _,player in pairs(players:GetPlayers()) do
	print(player.Name)
end

1 comment

0

Thanks!

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