User:Anaminus/for nutshell: Difference between revisions
>Anaminus 'for' in a nutshell |
>Anaminus mNo edit summary |
||
Line 1: | Line 1: | ||
{{CatUp|User:Anaminus}} | |||
='''The 'for' statement, in a nutshell:'''= | ='''The 'for' statement, in a nutshell:'''= | ||
Latest revision as of 08:09, 12 April 2008
The 'for' statement, in a nutshell:
'for' statement: Repeats a piece of code through the variables specified.
Format:
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:
Stepping by twos:
for n = 0,10,2 print(n) end
'0' will print in the output.
'2' will print in the output.
'4' will print in the output.
'6' will print in the output.
'8' will print in the output.
'10' will print in the output.
This also works for stepping down...
for i = 9,0,-3 do print(i) end
'9' will print in the output.
'6' will print in the output.
'3' will print in the output.
'0' will print in the output.
The default step is 1...
for p = 1,3 do print(p) end
'1' will print in the output.
'2' will print in the output.
'3' will print in the output.
Tables:
The 'for' statement is often used to do something to each object in a table.
table = {"A","B","C"} for i = 1,#table do print(table[i]) end
'A' will print in the output.
'B' will print in the output.
'C' will print in the output.
Note:
'#' 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.
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