Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to use Generic For?

Asked by 9 years ago

How do you use Generic For loops or whatever they're called. I read this in the ROBLOX wiki and was totally confused even though I read all of the other beginner scripting tutorials.. :)

1 answer

Log in to vote
3
Answered by
MrFlimsy 345 Moderation Voter
9 years ago

This was answered here.

A generic for loop looks like this:

for index,value in pairs(table) do

end

The variables index and value can be replaced with anything. table should be a valid table.

The code will loop through once for every value in the given table. Each time it loops, the 'value' variable will be equal to the value it's currently passing over, and 'index' will be equal to the number of times it's already looped. In programming lingo, this is called an iterator.

Here's an example:

local stuff = { "Apple", "Pear", "Orange" }

for i,v in pairs(stuff) do
    print(i)
    print(v)
end

--[[

Output:

1
Apple
2
Pear
3
Orange

]]

Hope this helped!

Ad

Answer this question