Could somebody explain for i, v in pairs

But you still gave a false implication by not stating that order is not guaranteed and showing the print in order. The problem isn’t that you typed it out in order, it’s that you didn’t mention that order is not specific. I shouldn’t have to explain what implications are.

3 Likes

It is basically an enhanced for loop. The i, v is defining variables for each i ndex and v alue of the table that you are iterating through. k for key is often used rather than i in most cases. pairs is your iterating function, it returns each index and value of the table. Another not so common one is ipairs , which functions the same for the most part except that it will stop the loop once it runs into a non-existent ( nil ) value. For example:

local myTable = {5, "pineapple", [23] = 6, ["foo"] = true}
for key, value in pairs(myTable) do
    print(key, value)
end
1       5           -- because we didn't define a key for the value 5, it defaulted to index 1.
2       pineapple   -- same case here, except they index is now 2.
23      6           -- we defined a key by using square brackets and we set the index to 23.
foo     true        -- keys can also be strings, and we can store any value we want in a table.
12 Likes

You shouldn’t iterate over an Instance’s children using pairs, it’s the least optimal for loop. For arrays, though both pairs and ipairs will work, using numerical for loops is optimal.

2 Likes

Very well explained, Crazyman32! Your answer halp me a lot understanding how it works :slight_smile:

3 Likes

@viindicater
I think you forgot the commas.

t = {
[“One”] = “The First”,
[“Two”] = “The Second”,
[“Three”] = “The Third”,
}

1 Like

Numeric for loops: Programming in Lua : 4.3.4
Generic for loops: Programming in Lua : 4.3.5

I am confident enough to say that any other sources than the ones specified above, should be ignored.

2 Likes

In simple terms, basically it means it goes through the selected values of a table.

1 Like

In summary the:

i,v

means that it runs through its key word, and then value, such as key value and key2 value

1 Like

this was solved so long ago I use it a lot now

2 Likes

then, print(i) will print key and key2
and print(v) will print value and value2 ?

1 Like

That is correct.

This:

for key, value in pairs(table) do
     print(key) -- this is i!
end

will write:

key
key2

into the console.

3 Likes

Whats the difference between _, v and i, v?

2 Likes

It’s just different variable naming. _ usually indicates that it isn’t used in the code.

1 Like
1 Like

Can you give me an example of this loop? (Checking children)

1 Like

GetChildren returns a numerically indexed table with the value of each index being the object.

local Children = game.Workspace:GetChildren()

for Index, Child in ipairs(Children) do
        if  Child.Name == "Baseplate" then
        print(Index)
        end
end
1 Like

I understand your issues and I also understand how frustrating it is to try and understand a concept whilst complicated language is being used even though these are very precise and carefully formulated responses by incredible people, way above my skill level. That being said, I will try to explain it in the simplest way possible without using too much technical language.

essentially, if you know what a for loop is in any programming language, it is a built-in loop that has specific conditions that need to be met for it to run with a specified set amount of times it will loop. In the case of for i,v in pairs, it is a built-in loop by Roblox.

What the for loop literally does is take a Table as an input in the pairs() and it loops over each position (The i means an index or the position of a value in a table) whilst also getting the value of the object in the position. This loop will end as soon as it goes over the last object in the Table and executes whatever code you have in the loop.

Here is an extremely simple bit of code that uses for i,v:

local WorkCont = game.Workspace:GetChildren() --puts everything in the workspace into a table

for i,v in pairs(WorkCont) do --Input the table we just created into this loop
	
	if v:IsA("Part") then --Check if the current object is a part
		
		v.Size *= 3 --Multiply the Part by 3
		
	end
	
end

This code will eventually go through every object in the workspace and multiply its size by 3.

The reason why this loop is so integral in so much code is because it returns a value for each indexed position which allows for things such as error correction, cleanup, easy linear searching, etc.

A few potentially applicable examples of this are:

  • Scanning a player’s inventory to see if they have a certain item to allow them to enter a dungeon door

  • Creating a character customisation menu that changes the skin colour of a character uniformly

  • Creating Environmental particle interactions

These are just some of the ways that you can apply this loop, but it has an infinite amount of use cases, you just need to be creative and see where it fits into your game. Some games may not even use it but nonetheless, it is a great tool to have in your toolkit when scripting.

I hope I haven’t made too many errors in this post, it is my first time posting on DevForums. Please correct any of my mistakes.

Ok so if your working with tables and you would like to sort them into a certain order via how many items that there is inside of the table aka indexed from the first item that has been added to the list to the last that would explain the key and item

Ex:
Table = { item_1,item_2,item_3}

—////////this is just to index to get a key out of the table\\\\
For indexed = 1,3,1 do
NewTabelValue = [indexed]
–///////// THE LINES ABOVE ARE GOING TO RETRIEVE THE INDEXED VALUE NOT THE VALUE ITSELF\\\\\\\\

Task.wait(0.012)
End
----/////////////\\\\\

–///////////////////THE LINES BELOW ARE GOING TO SORT THE ITEMS THREW A METHOD WITCH WOULD BE THE VALUE STORED UNDER (V) AND THE KEY WITCH IN THIS CASE WOULD BE W\\\\\\\\\\
do if W, V in Ipairs(Table) do
Print(V)–/////// this value is going to print out the value \\stored inside of the actual variable witch is stored memory \\\
Peint(W)–////// This value is going to be an active value Aka the value of the item in table \\

Task.wait(0.012)
End

Hello gggman0123, Kindly, I ask, what the hell is this garbage? Thank you.

4 Likes

Uhm
Find this button please
image