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

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

Asked by 10 years ago

How do you use a for loop, in lua?

2 answers

Log in to vote
0
Answered by 10 years ago

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.

Ad
Log in to vote
0
Answered by 10 years ago

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.

Answer this question