Basic block definition and invocation
To define a Gosu block, type use the backslash
character (\) followed
by a series of arguments. The arguments must be name/type pairs separated
by a colon character (:)
similar to the definitions of arguments to a method. Next, add a hyphen
character (-) and a greater-than
character (>) to form
the appearance of an arrow: ->.
Finally, add a Gosu expression or a statement list surrounded by braces
({}).
The syntax of a block definition is:
\ argumentList -> blockBodyThe argument list (argumentList) is a standard function argument list, for example:
x : int, y : intThe argument list defines the parameters to pass to the block. The parameter list uses identical syntax as parameters to regular functions. In some cases, you can omit the types of the parameters, such as passing a block directly into a class method such that Gosu can infer the parameter type.
The block body (blockBody) can be either of the following:
- A simple expression. This expression includes anything legal on the right-hand side of an
assignment statement. For example, the following line is a simple
expression:
"a concatenated string " + "is a simple expression" - A statement list of one or more statements surrounded by braces and separated by
semi-colon characters, such as the following simple single-statement statement
list:
\ x : int, y : int -> { return x + y }For single-statement statement lists, you must explicitly include the brace characters. In particular, note that variable assignment operations are always statements, not expressions. Thus, the following block is invalid:
names.each( \ n -> myValue += n )Changing the code to the following line produces a valid block:
names.each( \ n -> { myValue += n } )For multiple statements, separate the statements with a semicolon character. For example:
\ x : int, y : int -> { var i = x + y; return i }
The following block multiplies a number by itself, which is known as squaring a number:
var square = \ x : int-> x * x // No need for braces here
var myResult = square(10) // Call the block
The value of myResult
in this example is 100.
Standard Gosu style is to omit all semicolon characters in Gosu at the ends of lines. Gosu code is more readable without these optional semicolons. However, if you provide statement lists on one line, such as within block definitions, use semicolons to separate statements.
See also
