Interpolated Strings ("Hello ${name}")

Interpolated Strings ("Hello ${name}")

String interpolation in Luma allows embedding expressions inside string literals using the ${...} syntax. This enables dynamic and readable string construction, similar to modern high-level languages like Python and JavaScript.

Basic Syntax

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

Within a string, anything wrapped inside ${...} is treated as an expression, which is evaluated at runtime and converted to a string.

Embedded Expressions

You can embed not just variables but entire expressions:

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

This supports:

  • Arithmetic: ${x * y}
  • Function calls: ${to_str(123)}
  • Method calls: ${items.len()}
  • Any valid Luma expression

Default Values with “or”

You can provide a fallback value using the or operator:

name: str = ""
print("Welcome ${name or "Guest"}")  // Output: Welcome Guest

This is especially useful when working with optional or empty values. The expression ${name or "Guest"} returns "Guest" if name is falsy (e.g., "", nil, false).

Type Safety and Conversion

All interpolated values are automatically converted to strings using Luma’s internal _luma_sprint() function, ensuring consistent output regardless of data type:

pi: float = 3.1415
print("Pi is ${pi}")  // Output: Pi is 3.1415

Future Enhancements (Planned)

Feature Status Notes
Multi-line interpolation Supported Works inside triple-quoted strings (soon)
Nested expressions Supported Expressions inside ${…} are recursive
Custom formatting Planned ${price.format(“0.00”)} style formatting
Interpolation in comments Not planned Comments are ignored by design

Best Practices

  • Prefer interpolated strings for clean and readable output.
  • Use or for safe fallbacks with optional values.
  • Wrap complex logic in variables/functions before interpolating.

Examples

username: str = ""
score: int = 42

print("User: ${username or "anonymous"}")
print("Score: ${score * 2}")  // Output: Score: 84
Last updated on