sml

SML { ❄ }

中文 EN

Chapter 6: Environment Variables and Escaping

Chapter 6: Environment Variables and Escaping

This chapter discusses two small things that make configuration more secure and universal: environment variable injection andstring escaping.

6.1 Environment variables: $env.VAR

There are often sensitive values (API Key, password) or values that vary with the environment (domain name, port) in the configuration. Writing these in files is neither secure nor flexible. SML uses $env.VAR to read from environment variables during parsing:

secrets {
    resendApiKey: $env.RESEND_API_KEY
    dbPassword: $env.DB_PASSWORD
    optionalWebhook: $env.UNSET_WEBHOOK   # 未设置 -> 空串,不报错
}

main points:

-$env.VAR is locally replaced with the value of the environment variable (replaced with a string) during parsing.

-When the variable is not set, the result is an empty string**, and there will be no error (so you can write optional options with confidence).

-This configuration can be securely submitted to the repository, and the key only exists in the variables of the runtime environment.

Equivalent JSON must write plaintext to death; SML decouples “configuration” from “key”.

6.2 String Escaping

Common escaping supported in quotation string:

EscapingMeaning
\nLine Break
\tTab
\\Backslash itself
\"Quotation marks themselves
\u{XXXX}/\uXXXXUnicode code point, converted to UTF-8

Example:

banner: "SML \u{1F680} 上线 \n第二行\t制表"
label: "雪花 \u{2744} snow"
path: "C:\\Program Files\\app"

\u{2744} will be parsed into snowflake characters .

Escaping only takes effect within the quoted string. Bare words (values without quotation marks) do not support escaping, and special characters are enclosed in quotation marks.

6.3 Give it a try with your hands

  1. Write configuration reference environment variables:
   database {
       url: $env.DATABASE_URL
       pool: 16
   }
  1. Set DATABASE_URL=postgres://localhost/app before running the parser, and confirm that url is correctly filled in the parsing result.

  2. Try a field with emoji:

   greeting: "你好 \u{1F44B}"

→ [Chapter 7: Multilingual Use](/en/book/ch07 languages)

Hands on practice

After reading this chapter, directly modify SML in the editor below and click “Run” to immediately see the parsing results or validation errors - having output is necessary for efficient learning.

✍ 动手练习 写一个 secrets 块,含 apiKey: $env.RESEND_API_KEY 与 dbPassword: $env.DB_PASSWORD;再写一个 banner 字符串用 \u{1F680} 转义 emoji。
💡 提示:在浏览器里无法设真实环境变量,所以 $env.X 会解析为空串——这是预期行为,验证也据此判定。
✍ 自测考题:第 6 章自测:环境变量与转义 得分 0 / 4
Q1. 把环境变量注入值用哪个语法?
Q2. 浏览器里跑 playground 时,$env.X 通常解析成什么?
Q3. 判断:\u{1F680} 会在字符串里被转义成一个 emoji 字符。
Q4. 下面哪个转义是 SML 支持的?