| << Previous | Suneido > Contents > Language | Next >> |
A block is a section of code within a function. It can be called like a function, and can have parameters and accept arguments like a function. But blocks share local variables with the containing function.
Blocks are values. This means they can be assigned to variables, passed to other functions, etc.
Blocks are written as:
{ ... }
{ | x, y | ... }
Commas between parameters are optional.
Note: The "value" of a block is the value of it's last statement. On the other hand, an actual "return" will return from the function containing the block.
For example:
for_each = function (ob, block)
{
for (x in ob)
block(x)
}
sum = 0
for_each(#(1, 2, 3, 4), {|x| sum += x; })
Print(sum)
=> 10
A block immediately following a function call is interpreted as another argument. So the above example could also be written as:
for_each(#(1, 2, 3, 4))
{|x| sum += x; };
The block will be passed as "block: block".
One of the powerful aspects of blocks is that they can outlive the function call that created them. For example:
make_counter = function (next)
{ return { next++; }; };
counter = make_counter(10);
Print(counter());
Print(counter());
Print(counter());
=> 10
11
12
Note: Block parameters are independant from local variables with the same names in the containing function. i.e. If you have a block parameter called "x", the block will not be able to access "x" in the containing function, and any changes the block makes to it's "x" will not affect "x" outside the block. These block parameters will appear in the debugger preceded by an underscore.
| << Previous | Suneido > Contents > Language | Next >> |