Document interpolation.

This commit is contained in:
Bob Nystrom
2015-11-21 09:20:50 -08:00
parent 78655c68b0
commit 03163a760f
5 changed files with 29 additions and 7 deletions

View File

@ -8,7 +8,7 @@ System.print("Hello, world!")
class Wren {
flyTo(city) {
System.print("Flying to ", city)
System.print("Flying to %(city)")
}
}

View File

@ -56,7 +56,7 @@ it. Here's something to try:
Or a little more exciting:
:::wren
for (i in 1..10) System.print("Counting up " + i.toString)
for (i in 1..10) System.print("Counting up %(i)")
You can exit the interpreter using good old Ctrl-C or Ctrl-D, or just throw
your computer to the ground and storm off.

View File

@ -10,7 +10,7 @@ a familiar, modern [syntax][].
class Wren {
flyTo(city) {
System.print("Flying to " + city)
System.print("Flying to %(city)")
}
}

View File

@ -270,7 +270,7 @@ footer {
span.c1, span.cm { color: mix($code-color, $code-bg, 60%); }
// Keywords.
span.k, span.kd, span.kc, span.nb { color: hsl(200, 60%, 50%); }
span.k, span.kd, span.kc, span.nb { color: hsl(200, 70%, 50%); }
// Names.
span.vg { color: hsl(180, 70%, 35%); }
@ -278,11 +278,14 @@ footer {
span.vc { color: hsl(130, 60%, 40%); }
// Numbers.
span.m, span.mi, span.mf { color: hsl(30, 80%, 45%); }
span.m, span.mi, span.mf { color: hsl(90, 40%, 50%); }
// Strings.
span.s, span.s2 { color: hsl(40, 80%, 45%); }
span.se { color: hsl(45, 80%, 50%); }
span.s, span.s2 { color: hsl(40, 90%, 40%); }
// Escape.
span.se { color: hsl(50, 90%, 45%); }
// Interpolation.
span.si { color: hsl(50, 90%, 40%); background: hsl(40, 90%, 95%); }
// Operators and punctuation.
span.o { color: hsl(200, 40%, 50%); }

View File

@ -49,6 +49,7 @@ A handful of escape characters are supported:
"\0" // The NUL byte: 0.
"\"" // A double quote character.
"\\" // A backslash.
"\%" // A percent sign.
"\a" // Alarm beep. (Who uses this?)
"\b" // Backspace.
"\f" // Formfeed.
@ -77,6 +78,24 @@ Strings are instances of class [String][].
[string]: modules/core/string.html
### Interpolation
String literals also allow *interpolation*. If you have a percent sign (`%`)
followed by a parenthesized expression, the expression is evaluated. The
resulting object's `toString` method is called and the result is inserted in the
string:
:::wren
System.print("Math %(3 + 4 * 5) is fun!") //> Math 23 is fun!
Arbitrarily complex expressions are allowed inside the parentheses:
:::wren
System.print("wow %((1..3).map {|n| n * n}.join())") //> wow 149
An interpolated expression can even contain a string literal which in turn has
its own nested intpolations, but doing that gets unreadable pretty quickly.
## Ranges
A range is a little object that represents a consecutive range of numbers. They