-
Notifications
You must be signed in to change notification settings - Fork 0
Generators
Matthew edited this page Jul 4, 2018
·
3 revisions
Generators are functions that effectively pause and return a value whenever a yield statement is hit. They are defined just like functions, but use the generator keyword instead of fun.
generator int generator_func(int max)
{
for (let i = 0; i <= max; i++)
yield i;
}
You can use a generator by calling it, then calling MoveNext on the object that it returns until it returns zero. When it returns 0 it means that the function has returned.
let gen = generator_func(10);
gen.MoveNext();
let return_value = gen.Current();//this gets the value last yielded
This generator would return 0 the first time MoveNext is called, then 1 the next time, then 2, so on and so forth until it hits the max value.
You can also reset the generator back to the beginning by calling Reset
gen.Reset();