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

Where can I learn how to use i ,v in pairs and these type of loops?

1 answer

If you're more of a video guy, here you go:

PeasPod: https://www.youtube.com/watch?v=Jim-NPFSAFg -- he has a better tutorial for beginners.

PigHead10: https://www.youtube.com/watch?v=P80FXikQuJM

in short, the i,v in pairs loop is used to iterate through a table. It can search through the table and return either the index(i) or the value(v). Here's a quick example

Admins = {"DarkFlameCrimsonXana","LevelKap"}

	function AdminCheck(name)  -- made up the argument, you NEED to define it later in the player added script, or else the game won't know what "name" is
		for i, v in pairs(Admins) do
			if name == v then
				return true 
			end
		end
	end

this checks if the players name is in the admins list. the i part is the index or iteration and keeps track of how many times the loop has been run. So when it runs 1 time, it'll return i = 1, and v = "DarkFlameCrimsonXana" because you are the first index in the table.

Also, off the top of my head, i sometimes use this to change a property of parts for multiple instances.

Example:

Say we have 3 parts in the workspace, one name "Part1", "Part2", or "Part3" and we wanted to change their color to "Really red" we would use the in pairs loop, because it saves time instead of manually changing each part individually(not as useful now, but say you have thousands of parts!)

for i, v, in pairs(Workspace:GetChildren()) do -- GetChildren is a function that turns all the "children " of an object into a table and allows you to loop through it.
	if v:IsA("Part") then -- v is the value of whatever you loop through --IsA is a function that checks whether something is say a part, or a weld, or a shirt etc. It's bascially a way to sort through stuff and check if something is something.
		v.BrickColor = BrickColor.new("Really red") 
	end
end

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