Concepts - Iterators
What is an iterator?
Very simply, an iterator is a function that "iterates" over a certain thing using a for block until it cannot anymore! An example of an iterator that you'll learn quickly is the pairs iterator function.
Example
How do I write my own?
Iterators work through a little bit of for magic and a function that returns another function. They are divided into two steps.
Lets say for this example, you want to iterate over every character in a string
Step 1 - Initialization
First, we define our generator function that will act as our iterator, like pairs!
Next, we have two ways of going about things, we can either handle our own "state" or allow Lua to handle the iteration state for us.
Step 2.a - Handling our own state
If we want to handle our own state, we define it in our wrapper function locally as such.
Handling our own state comes with some benefits and some cons, one of the biggest benefits is our state doesn't have to be the first value returned by our generator.
Step 2.b - Lua handling our state
If we want to let Lua handle our state for us, we need to remember that the first value returned from our generator must be our state, otherwise it will be discarded.
Esoteric Information
There are extra values that are able to be passed after the iterator function call in for in loops.
"Invariant State"
Following the iterator function in a for in loop, you can provide something referred to as the "invariant state". This is essentially the constant (as in "invariant") data to be passed as the first argument to the function the iterator generator returns.
This is useful for a couple reasons, primarily, we can skip creating a generator entirely if we have a well defined function.
"Control Variable"
After our invariant state, we can provide a "control variable", this is our initial index variable!
Garry's Mod
Rust
Steamworks
Wiki Help