Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to use Generic For?

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

✓ Accepted answer

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!

This discussion is preserved as it was. New answers, comments, and votes are closed.