Invoking blocks

You can invoke blocks just like normal functions by referencing a variable to which you previously assigned the block. To use a block, type the following items in the following order:

  • The name of the block variable or an expression that resolves to a block
  • An open parenthesis
  • A series of argument expressions
  • A closing parenthesis

For example, suppose you create a Gosu block with no arguments and a simple return statement:

var blockWithStatementBody = \-> { return "hello blocks" }

Because the statement list returns a String, Gosu infers that the block returns a String. The new block is assigned to a new variable blockWithStatementBody, and the variable has a type of String even though the code text does not show the type explicitly.

To call this block and assign the result to the variable myresult, use this code:

var myresult = blockWithStatementBody()

The value of the variable myresult is the String value "hello blocks" after this line executes.

The following example creates a simple block that has two numbers as parameters and returns the result of adding those numbers:

var adder = \ x : int, y : int -> { return x + y }

After defining this block, you can call it with code such as:

var mysum = adder(10, 20)

The variable mysum has the type int and has the value 30 after the line is executed.

You can also implement the same block behavior by using an expression rather than a statement list, which uses an even more concise syntax:

var adder = \ x : int, y : int -> x + y