Interpolated strings

Interpolated strings

Luma can put values into a string with ${...}, like many modern languages (JavaScript, Kotlin, Python’s f-strings):

name: str = "Luma"
print("Hello ${name}!")

Output:

Hello Luma!

Any expression

${...} holds an expression, not just a variable name. It is evaluated when the string is created, and its value becomes text:

a: int = 10
b: int = 20
print("Total: ${a + b}")

score: int = 42
print("Score: ${score * 2}")

nums: [int] = [1, 2, 3]
print("first: ${nums[0]}, count: ${len(nums)}")

Output:

Total: 30
Score: 84
first: 1, count: 3

How values become text

Values are shown exactly as print shows them:

pi: float = 3.1415
ready: bool = true
tags: {str} = {"new", "sale"}
err: error = nil
print("Pi is ${pi}, ready: ${ready}, tags: ${tags}, error: ${err}")

Output:

Pi is 3.1415, ready: true, tags: {"new", "sale"}, error: nil

A string value is inserted as it is, without quotes. Strings inside a list, map or set are shown in quotes, as print does.

An interpolated string is a str

The result is an ordinary str: you can store it, compare it, put it in a list. Interpolation is also how strings are joined in Luma:

first: str = "Ada"
last: str = "Lovelace"
full: str = "${first} ${last}"
print(full)
print(full == "Ada Lovelace")

Output:

Ada Lovelace
true

Strings and braces inside $

An expression inside ${...} may contain strings, which may be interpolated themselves, and even map or set literals:

name: str = "Luma"
print("nested: ${"inner ${name}"}")
print("a map: ${ {"k": 1} }")

Output:

nested: inner Luma
a map: {"k": 1}

Writing a $

A $ that is not followed by { is ordinary text. To write ${ itself, escape the dollar sign: \$.

print("Price: $5")
print("Write \${name} to insert a name")

Output:

Price: $5
Write ${name} to insert a name

Errors

  • ${} with nothing inside, and a ${ without its }, are compile errors.
  • ${...} holds exactly one expression: "${1 2}" is an error.
  • Like any string, an interpolated string must end on the line it starts on.
  • An error raised while evaluating ${...}, such as an index out of range, is raised as usual and can be caught with try.

Best practices

  • Prefer interpolated strings for clean and readable output.
  • Keep the expressions short. Put complex logic in a variable first, and interpolate the variable.
  • For a number of decimals, use a float’s decimals: "${price.decimals(2)}".

Not available yet

Old Luma also had these, which are not in this version:

  • A fallback with or: "${name or "Guest"}".