Difference between revisions of "Loops"

From PZwiki
Jump to: navigation, search
(Created page with "Loops allow the user to control the user how many times a piece of code is ran. There are three main types of loops used in Lua: ''for'', ''while'' and ''repeat''. ''while'' loop...")
(No difference)

Revision as of 16:46, 20 January 2013

Loops allow the user to control the user how many times a piece of code is ran. There are three main types of loops used in Lua: for, while and repeat. while loops are not supported in PZ, so will only be mentioned very briefly.

For Loops

For loops have the following format:

for local_variable = start_number, end_number, step do
--statements go here
end

For example:

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

In the above example 'step' is not specified, so Lua assumes it is +1. However, we can specifiy step to a decimal or negative number:

for i = 10, 1, -0.5 do
print(i)
end

If Lua detects that the loop will never reach the end number, it simply won't run. Note that i used in the example is a local variable, so that any changes made to it are only done inside the chunk:

s = 10
e = 15

for i = s, e do
print("Start i: ".. i, "Start s: " .. s)
i = i+i
s = s+s
print("End i: " .. i, "End s: " .. s)
end

print("Final: " .. tostring(i), s)

While loops

While loops are not supported by PZ (although this isn't strictly true), however it is worth knowing if you use Lua outside PZ. while looops tests a condition to see whether it is true, and repeats its statements until it is. They have the following format:

while condition_is_true do
--statements
end

For example:

i = 1

while i < 5 do
print(i)
i = i+1
end

Repeat Loop

Repeat loops are similar to while loops, except the condition is tested at the end of the loop, meaning it always runs at least once. They have this format:

repeat
--statements
until condition_is_true

Note that unlike for and while loops it does not need an end or do. Using the same example as the while loop:

i = 1

repeat
print(i)
i = i+1
until i > 5

As already stated, repeat loops always run at least once regardless:

i = 6

repeat
print(i)
i = i+1
until i > 5

print(i)

Summary

  • for loops can numerically dictate how many times code is run
  • The step of a for loop is assumed to be +1 if not specified
  • while loops repeat while its condition is not true
  • while are not properly supported in PZ
  • repeat loops are similar to while loops, but always run at least once