I've seen many scripts use the format
for i, v in pairs do
and use
for i = 1,length,1
in their scripts. I've been searching it up on the developer wiki, but I've found no clue to what it is used for.
What can (i, v for) do?
I've seen many scripts use the format
for i, v in pairs do
and use
for i = 1,length,1
in their scripts. I've been searching it up on the developer wiki, but I've found no clue to what it is used for.
What can (i, v for) do?
Typically used for looping,
for i, v in pairs(workspace:GetChildren()) do
print(i,v)
end
It returns each object along with a number, i is the number and v is the object.
Output from code I sent above:
Terrain Camera Baseplate
On the other hand
for i = 1,100,1 do
print(i)
end
That would be a way to increment a value.
if you printed i, in the output it would show all the numbers up to 100, this can be useful for different effects like transparency and tweens, etc..
Note that you can use tables in for loops
local table = {"Hi", 50, "bob"}
for _, v in pairs(table) do
print(v)
end
Hi 50 bob
Also _ is used when you don't need it, we don't need it right now because we aren't indexing a specific item in the table. If we did, the code would look like this:
local table = {"Hi", 50, "Bob"}
for i, v in pairs(table) do
if i == 3 then
print("Table value indexed: ",v)
end
end
Table value indexed: Bob
This can also just be shortened to
print("Table value indexed: ",table[3])
Table value indexed: Bob
This discussion is preserved as it was. New answers, comments, and votes are closed.
8 comments
Make sure if this helped to upvote and accept answer
If you have questions feel free to reply here
Quick Note: in "for i,v in pairs", people generally use i,v as it stands for index and value
Yup
People that are new to programming don't generally know what an index is. Or at least I believe they don't
thanks for the help
np
This is a great toturial! Too bad I need 25 reputation to upvote but you have my appreciation :D