Gosu String templates

In addition to simple text values enclosed by quotation marks, you can embed Gosu code in the definition of a String literal. At compile time, Gosu uses its native type checking to ensure that the embedded Gosu code is valid and type safe.

Embedding a Gosu expression into text

Use the following syntax to embed a Gosu expression in the String text:

${ EXPRESSION }

If the expression does not return a value of type String, Gosu attempts to coerce the result to the type String.

For example, suppose you need to display text with a calculation in the middle of the text:

var mycalc = 1 + 1
var str = "One plus one equals " + mycalc + "."
print(str)

Instead of this multiple-line code, embed the calculation directly in the String as a template:

var str = "One plus one equals ${ 1 + 1 }."
print(str)

This code prints:

One plus one equals 2.

Embedding Gosu statements into text

To embed one or more statements, which do not return a value, in String text, you use a template scriptlet. Use the two-character text <% to begin the scriptlet. Use the two-character text %> to end the scriptlet:

<% STATEMENT LIST %>

Gosu runs the statements in the scriptlet before evaluating the text in the string.

The following code shows the use of scriptlets in a String value:

var str = "<% for (i in 1..5) { var odd = (i % 2 == 1) %>${i} is ${ (odd?"odd":"even") }\n<% } %>"
print(str)

This code prints:

1 is odd
2 is even
3 is odd
4 is even
5 is odd

Quotation marks in templates

Within a code expression or statement inside a template, do not escape quotation mark characters by using a backslash character. The following line is valid Gosu code:

var str = "<% var myvalue = {"a", "b"} %>"

The following line is invalid because of incorrect escaping of the internal quotation marks:

var badStr = "<% var bar = {\"a\", \"b\"} %>"

See also