I have been able to use for i,v in pairs (()) do
in some of my own scripts but I've never actually known what it means.
Think of it like this: v is the
value
of i and i is theindex
or position of the table.
Similar to a simplified for loop
, where for i equals #1 until it equals #2 do. This meaning that i continues going from #1 until #2. Repeating the code in the for loop
until the i equals #2.
for i = #, # do end
But, with a for loop
like this, it's like, for the amount of indexes
in the table, in pairs
(meaning the code inside the loop runs again and again until it's gone through the amount of indexes
which is the amount of things inside a table. Where the value
is what the index
equals, say array = {true, false} for the amount of things inside the array
, it will repeat the code for all the values
, in order.
Ex:
local table = {true, false} for index, value in pairs (table) do print(value) end
Output:
true false
Running the code printing index
rather than value
, will give you the position of the values
, the output would look like this:
1 2
for i,v in pairs () do
is an iterative loop. While it may sound like sort of a doozy at first, all it takes is a basic understanding of Tables/Arrays.
A table/array is made doing the following:
local array = {term 1, term 2, term 3,etc}
Say you wanted to print the array, the standard form of this is print(array[Index])
where the index is the order the term is in.
local newArray = {"Hello", workspace.Part, "Potato"} print(newArray[1]) --Prints Hello print(newArray[2]) --Prints Part (Will absolutely verify later) print(newArray[3]) --Prints Potato
Just printing the terms alone was a hassle and kind of defeats the point of bundling everything up into a neat array. Luckily for us, the for i,v
Iterative loop can handle that for us.
By simply doing
for i,v in pairs(newArray) do print(i,v) --Prints 1 Hello, 2 Part, 3 Potato
It is a lot easier and resource friendly to have a loop do that and end itself rather than try some magic with an infinite loop such as while true do
. From there treating v or the variable in that position as a property for everything in the table unlocks easy to group changes and deletions using your code.
If you have any more questions feel free to ask, the Roblox Wiki page on Arrays is also very helpful as it goes into a lot more depth.
~MBacon15