Several languages, such as JavaScript, C#, and Python, have "generator" methods that lazily yield a series of values rather than returning a single one:
function* upToThree() {
for (let i = 1; i < 3; ++i) {
console.log(`In generator, i = ${i}`);
yield i;
}
}
let g = upToThree();
console.log('Before the loop');
for (const el of g)
console.log(`In loop, got ${el}`);
/* Console:
Before the loop
In generator, i = 1
In loop, got 1
In generator, i = 2
In loop, got 2
*/
While this feature is convenient to have, it's not obvious how to implement them, especially in a compiled language: local variables can't necessarily be stored on the stack, as the generator could be partially iterated and then passed somewhere else.
What are some strategies for implementing generators?