What is a For I in pairs loop?

Okay, I know this sounds extremely stupid but no matter how hard I try, I just can’t seem to figure out what this code is! I have watched so many tutorials and even read a book, with no answer. What is it? What does it do? What are the arguments? I just have so many questions! I want to use it in some way because it seems helpful to others. If you are going to reply, thanks!

for i, child in pairs() do

pairs is an iterator function that requires a table. The parameters it passes to the for loop are the index and the value. It works well with dictionaries.

1 Like

When using this, you “go through” a table. It’s basically a function that will run again, and again until the list is finished. v is the object, and i (I prefer k for key) is the key of the table, really only used for dictionaries.

In a pairs loops i is simply a variable name and a key's name

For example:

local dictionary = {
   ["First"] = "1st",
   ["Second"] = "2nd",
   ["Third"] = "3rd",
   ["Cat"] = "Not Real"

--Print the stuff
for i, v in pairs(dictionary) do
   print(i, "equals", v)

This would print out, in an unordered fashion:

Third equals 3rd
First equals 1st
Cat equals Not Real
Second equals 2nd

Like I said earlier i is simply a variable name for a key, so you can rename it to whatever you want. Which I recommend as it will make the loop easier to read while coding.

for key, value in pairs(dictionary) do
   print(key, "equals", value)

This will still print the same result but with just renamed variables.

If you would like to know more check out the roblox dev docs:

1 Like