Repository navigation
Variable Expansion
Chris Michael edited this page Oct 7, 2026
·
1 revision
With withExpansion(), unquoted and double-quoted values replace references to other variables:
module Ex03Expansion
import Std.Io as Io
import Std.Map as Map
import PuduLangEnvironment.Loader as Loader
import PuduLangEnvironment.Options as Options
import PuduLangEnvironment.Source as Source
const LINES: Array[Str] = [
"EMPTY=",
"A=$\{UNSET:-fallback\}",
"B=$\{EMPTY:-used because empty\}",
"C=$\{EMPTY-kept empty\}",
"D=$\{UNSET:-$\{HOME\}/cache\}",
"E=\\$HOME stays literal",
"F=$HOME/data"
]
export fn main() -> Int {
let options = Options.defaults().withSources(&[Source.Text("example", LINES.join("\n"))]).withExpansion()
match Loader.readOver(&options, &Map.fromPairs(&[("HOME", "/home/ada")])) {
case Ok(values) => {
for pair in values.entries() { let _shown = Io.writeLine(pair[0] + " = " + show(pair[1])) }
0
}
case Err(_) => 1
}
}
Output:
A = "fallback"
B = "used because empty"
C = ""
D = "/home/ada/cache"
E = "$HOME stays literal"
EMPTY = ""
F = "/home/ada/data"
| Form | Answers |
|---|---|
$NAME, ${NAME}
|
the value of NAME, or nothing when unset |
${NAME:-fallback} |
the fallback when NAME is unset or empty |
${NAME-fallback} |
the fallback only when NAME is unset |
\$NAME |
a literal $NAME; an even run of backslashes before $ is halved and the reference still expands |
$1, $-, a trailing $, an unclosed ${
|
a literal $
|
A name is looked up first among the assignments made before it — in this file or an earlier one — and then in the process environment. A value is expanded once, when it is assigned: what a reference answers is final text and is never expanded again, so a literal $ stays literal wherever the value is used, and no two values can refer to each other without end. A fallback is itself expanded, so ${PORT:-${DEFAULT_PORT}} chains.
Expansion reads a snapshot of the process environment taken once per load, so a file of a thousand references reads the environment once.