You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Matthew edited this page Mar 25, 2015
·
1 revision
#Functions
A function can be defined in one of two ways.
fun add(a,b)
{
return a+b;
}
or
add = fun(a,b)
{
return a+b;
}
If a function completes execution without returning, it implicitly returns a null value.
#Generators
Generators are functions that pause and return a value whenever a yield statement is hit.
A generator is returned by any function that uses the yield keyword.
fun generator_func()
{
for (local i = 0; i < 10; i++)
yield i;
}
generator = generator_func();
This generator would return 0 the first time it is called, then 1 the next time, then 2, so on and so forth until it hits 9.
When the generator is run after it hits nine, it hits an implicit "return null;" statement and returns null.
Then, the generator is finished and will throw an error if it is called again.
In order to check when a generator has returned, you can check the result of the ":done()" function on it as shown below.
local finished = generator:done();
It is also possible to use generators in a for each loop.