Molten

Strings

A string is immutable UTF-8 text. String literals are static; building a new string allocates it from an arena, the frame arena by default.

export function main(): void {
    const name = "Coin";
    const count = 3;
    const label = `${name} x${count}`;          // a template string, built in the frame arena
    const joined = name + " " + true + " " + 2.5;
    print(label, joined);
    print(label.length, label[0] ?? "?", label[99] ?? "none", label.slice(-2));
    print(string(42), (7).toString(), label == "Coin x3");
    const text = "h\u{e9}llo \u{1f600}";
    print(text, text.length);
}
Coin x3 Coin true 2.5
7 C none x3
42 7 true
héllo 😀 7

What you can do with a string

Operation Result
a + b, `...${x}...` A new string. Operands may be strings, numbers or bools. Built in frame
s += x Builds a new string and assigns it
s.length Number of Unicode characters (scalar values), not bytes
s[i] A one-character string | null; null outside the string
s.slice(start?, end?) A view of part of the string. Negative indexes count from the end; out-of-range ends are clamped
string(x) Converts a string, number or bool
n.toString() Converts a number (no arguments)
==, != Compare bytes
new(game) string(a, b, ...) Joins the parts into the named arena
  • Templates and + accept strings, numbers and bools only: template interpolation requires a string, number, or bool.
  • Numbers do not convert to strings implicitly in assignments: const s: string = 5; gives cannot convert int to string.
  • Strings can't contain a NUL character.
  • There are no string methods beyond these (no split, indexOf or toUpperCase).

Lifetime

Built strings live as long as their arena:

  • A string built during a tick (frame) is valid until the end of the frame. That is perfect for uiSetText, print and other calls that copy it.
  • To keep a string longer, allocate it in a longer-lived arena: new(game) string("Player ", 1). A component can only hold a string in a @transient field.
  • A slice or index of a string lives as long as the original.
  • new(heap) string(...) must be released with free(s).

The compiler rejects storing a frame string somewhere that outlives the frame when it can tell (frame allocation escapes into game storage). See Memory.

Strings in a game

uiSetText(name, value) copies the text into engine memory, so passing a template string is fine. saveRead(name) returns frame-lifetime text; copy it with new(game) string(...) if you keep it.

View this page's source on GitHub