If so, I've never heard of it before, if there isn't any, I am sorry for posting.
Don't be sorry for posting, that's what this website is for!
The only thing you're missing the generic for loop. It looks like this:
for index,value in pairs(table) do end
The variables index
and value
can be replaced with anything. table
should be a valid table.
The code will loop through once for every value in the given table. Each time it loops, the 'value' variable will be equal to the value it's currently passing over, and 'index' will be equal to the number of times it's already looped. In programming lingo, this is called an iterator.
Edit: Here's an example:
local stuff = { "Apple", "Pear", "Orange" } for i,v in pairs(stuff) do print(i) print(v) end --[[ Output: 1 Apple 2 Pear 3 Orange ]]
Lua has three kinds of loops. while
, repeat
, and for
.
While loops go like this:
while condition do body end
Basically, when you get to the loop, you look at the condition
.
If it's falsey, skip to the end. If its truthy, run body
and then start over, checking the condition again.
Repeat loops are a lot like while loops. They look like this:
repeat body until condition
You can rewrite them as while-loops like this:
body while condition do body end
Basically, they always run their inside once before checking the condition. Usually, it's better to use while-loops, but these are occasionally useful.
For loops are the most special. There's the kind you mentioned:
for i = 1, 5 do print( i ) end
This will print 1 2 3 4 5
.
But they can do more than just that! You can choose an increment size:
for i = 0, 10, 2 do print( i ) end
This prints 0 2 4 6 8 10
For loops also allow the use of iterators. The most famous iterators are pairs
and ipairs
.
An iterator is a function that when called, produces some output. When you call it again, it produces a different output, and so on. For instance, this generator will produce the numbers 1 to 10:
function oneToTen() local i = 0 return function() i = i + 1 if i > 10 then return nil end return i end end
So if we do:
for i in oneToTen() do print( i ) end
Or if we want to print the first 20 squares, we can do this:
function squares() local i = 0 return function() i = i + 1 if i > 20 then return nil end return i^2 end end
And now we can do:
for n in squares() do print( n ) end
Iterators are extremely powerful, but they can be tricky to write. ipairs
and pairs
are iterators which iterate over tables, for instance, and they're used all the time.
only
while wait() do
and
math.huge