locale

tape
import locale from "locale";

locale.set("fi");                 // all @t("...") strings in Finnish from now on
io.println(@t("Good morning!"));  // "Hyvää huomenta!"

locale chooses which language the program’s translatable strings are shown in. The strings and their translations are written with @t("...") and the #localization region; the compiler builds the translations into the program, and @t looks them up in the active locale. You only import locale to choose or inspect the locale. It is a capability module: it reads the environment.

The active locale

FunctionDoes
set(code)Use code from now on (normalized); "" shows the source strings
get() -> stringThe active code, normalized; "" when none
use_env()Go back to the locale the environment names
env_code() -> stringThe code the environment names, "" when none
normalize(name) -> string"fi-FI.UTF-8" → "fi_FI"; "C", "POSIX" and invalid names → ""
pick(langs) -> ?i64Which of langs the active locale picks, as @t does
available() -> []const []const u8Every language of the program’s #localization regions, sorted

A program starts in the locale its environment names: the first of LC_ALL, LC_MESSAGES and LANG that is set and not empty. The charset and modifier are dropped and - becomes _, so LANG=fi_FI.UTF-8 is fi_FI. C and POSIX mean no locale: the source strings.

plaintext
LANG=de_DE.UTF-8 ./app      # German, if the program has it
LC_ALL=C ./app              # the source strings

On Windows these variables are normally not set, so a program shows its source strings until it calls locale.set (for example from a setting or a --lang option).

Which translation is shown

For the active code, say fi_FI:

  1. the fi_FI translation,
  2. else the translation of its language part, fi,
  3. else the source string.

Codes compare without regard to case (fi_fi is fi_FI). set never fails: a code the program has no translations for shows the source strings.

tape
locale.set("de_AT");
io.println(@t("Good morning!"));   // the "de" translation
locale.set("pt");
io.println(@t("Good morning!"));   // "Good morning!" — no pt translation

Offering a choice

available() lists the languages the program’s #localization regions translate into, for a language menu:

tape
for (code in locale.available()) {
    io.println(code);              // "de", "fi", "sv", ...
}

Notes

  • Codes are identifiers: letters, digits and _, at most 32 bytes.
  • Translations can’t be loaded from a file at run time yet; they are part of the program.
  • Not available in t0.

Last modified: