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

Can somebody explain how to use a 'for' loop?

How do you use a for loop, in lua?

2 answers

An example of a for loop would be

for i = 1, 10 do
	print(i.." ")
end

and it would OUTPUT 1 2 3 4 5 6 7 8 9 10

The "i" can actually be anything, you could actually just name it "BugQuestioner" and if you refer to it later as BugQuestioner it will work. Also the 1 after the equals is the initial starting value and the number after the comma is the end value. If you want it to count down you can switch the 1 and the 10 and add another comma and put -1 because that's the number it will increment by. If you don't set the increment it will default to 1.

Okay, so here is how it is written first of all.

myTable = {1,2,3,4,5}

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

So i'm assuming you learned what a table is. If not here's what it is: A table is a variable that contains numbers,strings etc. It could hold anything as long as it has a value.

A For Loop loops through the table, by going through each object/string/number within. V represents the object it's currently counting.

So this will print 12345. But not in any order. That's what table.Sort() is for.

myTable = {1,2,3,4,5}

for i,CurrentObject in pairs(InsertTableNameHere) do
       print(v) -- Loops through all objects in the table and will print each one.
end

Hope i helped.

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