All pastes #947190 Raw Edit

'for' in a nutshell

public text v1 · immutable
·published 2008-03-18 08:29 UTC
rendered paste body
The 'for' statement, in a nutshell: 

'for' statement: Repeats a piece of code through the variables specified. 

for i = B,F,S do end 

i = The variable. 
B - Number where the variable starts. 
F - Number where the variable should stop. 
S - Number that is added to the variable each repeat. 

Example: 

for i = 1,3 do 
number = i 
end 

The first time around, 'number' will equal 1. The second time around, 'number' will equal 2. The third time around, 'number' will equal 3. At that point, because 'i' has reached the limit (which is 3), it will stop repeating. 

More Examples: 

for n = 0,10,2 print(n) end 
prints out... 

0 
2 
4 
6 
8 
10 

This also works for stepping down... 

for i = 9,0,-3 do print(i) end 
prints out... 

9 
6 
3 
0 

The default step is 1... 

for p = 1,3 do print(p) end 
prints out... 

1 
2 
3 

------------------------------------------------------------------------------------------ 

Tables: 

The 'for' statement is often used to do something to each object in a table. 

Example: 

table = {"A","B","C"} 

for i = 1,#table do 
print(table[i]) 
end 

prints out... 

A 
B 
C 

'#' returns the number of objects in a table, which in the example, is 3. 
'[]' gets an individual object of a table. So, in the previous example, 

table[2] 
returns 
"B" 

------------------------------------------------------------------------------------------ 

"GetChildren()" function: 

The GetChildren() function returns a table of all abjects located within the object it was called with. 

Example: 

Say that Bob, Mary, and John, are in your place, and you wanted to get each of their names. You'd start out with the GetChildren() function, 

players = game.Players:GetChildren() 

if we were to write the table out manually, it would look like this, 

players = {"Bob","Mary","John"} 

Now you want to print out each of their names. So you'd use a '#' to get the number of objects in the table, and the '[]' to get an individual object in the table, 

for n = 1,#players do 
print(players[n].Name) 
end 

This would appear in the output: 

Bob 
Mary 
John 

------------------------------------------------------------------------------------------ 
For futher information, see the following sites: 

http://lua-users.org/wiki/ForTutorial 
http://lua-users.org/wiki/TablesTutorial 


?-Anaminus-?