Game Development Reference
In-Depth Information
print(i)
i=i
-
1
end
There
s nothing fancy here. As with
if
statements, there are no curly braces. The
loop block is between the
do
and
end
keywords.
'
for
Lua has two flavors of
for
loop. The first is the numeric form, which is very similar
to what you
'
d find in C. The second is the generic form, which is a handy shorter
form typically used for tables. The numeric form looks like this:
for i = 1, 10, 1 do
-- do stuff here
end
As with the
while
loop, the
do
and
end
keywords define where the inner scope of
this loop is. The first part of the
for
declaration sets a local variable to the value of 1.
(Note that the
local
keyword is not required in this specific case;
for
loop counter
variables are always local.) The second part of the declaration is the limit and will
cause the loop to exit once it
s reached. The third part of the declaration is the step,
which adds that value to the variable. If you omit the third statement entirely, Lua
will assume you want to increment the variable by 1, so this part is unnecessary
unless you want something else. This loop will do exactly the same thing:
'
fori=1,10do
-- do stuff here
end
Note that Lua evaluates the limit inclusively. In other words, it checks to see if
i
is
less than or equal to the value. The above loop will execute 10 times.
The generic form of the
for
loop works using iterator functions. On each iteration,
the function is called to produce a new value and breaks out when the function
returns
nil
.
prime = { 2, 3, 5, 7, 11 } -- the first five prime numbers
for index, value in ipairs(prime) do
print(index, value)
end
This chunk will loop through the
prime
table and print out the index and value for
each element in the table. The
ipairs()
function is a built-in Lua iterator function
that returns the next index/value pair until the end of the table is reached. Note that
this function only works for the array portion of the table. If you need to see the hash