Tutorial by Examples

Iterators utilize a form of the for loop known as the generic for loop. The generic form of the for loop uses three parameters: An iterator function that gets called when the next value is needed. It receives both the invariant state and control variable as parameters. Returning nil signals term...
The Lua standard library provides two iterator functions that can be used with a for loop to traverse key-value pairs within tables. To iterate over a sequence table we can use the library function ipairs. for index, value in ipairs {'a', 'b', 'c', 'd', 'e'} do print(index, value) --> 1 a, ...
Both pairs and ipairs represent stateless iterators. A stateless iterator uses only the generic for loop's control variable and invariant state to compute the iteration value. Pairs Iterator We can implement the stateless pairs iterator using the next function. -- generator function which initial...
Stateful iterators carry some additional information about the current state of the iterator. Using Tables The addition state can be packed into the generic for loop's invariant state. local function chars_iter(t, i) local i = i + 1 if i <= t.len then return i, t.s:sub(i, i)...

Page 1 of 1