Skip to content

Reads, writes, encodes and decodes YAML. Mappings and sequences become Lua tables, numbers and booleans become Lua numbers and booleans, and a YAML `null` becomes `nil`, so keys with a null value are absent from the table. Decoding is safe: tags that create Java objects are refused and recursive aliases are an error. Only the first YAML document of a text or file is supported. An unquoted date such as `2024-03-05` is typed as a timestamp by YAML and comes back as a date string like `Tue Mar 05 01:00:00 CET 2024`, not as `2024-03-05`: put dates in quotes. When encoding, a table is written as a sequence if its keys are 1..n and as a mapping otherwise, in block style with two-space indentation. Mapping keys come out in Lua's table order.

  • Kind Library, a global in every script
  • Category APIs & Data
  • Functions 4

Functions

  • open any Reads a YAML file and decodes it like `Yaml.decode`.
  • decode any Decodes YAML text.
  • encode string Encodes a table, string, number, boolean or `nil` as YAML text.
  • write self Encodes a value like `Yaml.encode` and writes it to a file, replacing the file if it exists and creating missing directories.
Yaml.open(file: string)→any

Reads a YAML file and decodes it like `Yaml.decode`. Throws `Failed to read YAML file` when the file cannot be read and `Failed to decode YAML file` when it is not valid YAML or holds more than one document.

Parameters

file string
YAML file to read, relative to the workspace

Returns

any The decoded value: a table for a mapping or sequence, otherwise a string, number, boolean or nil

Example runs in CI

Yaml.write("settings.yaml", { name = "demo", retries = 3 })
local settings = Yaml.open("settings.yaml")
print(settings.name, settings.retries)
Yaml.decode(yaml: string)→any

Decodes YAML text. Empty text gives `nil`. Numbers become Lua numbers; quote a value (`"007"`) to keep it a string. Throws `Failed to decode YAML` with the parser message when the text is not valid.

Parameters

yaml string
YAML text to decode

Returns

any The decoded value: a table for a mapping or sequence, otherwise a string, number, boolean or nil

Example runs in CI

local config = Yaml.decode("name: demo\nretries: 3")
print(config.name, config.retries)
print(Yaml.encode({ enabled = true }))
Yaml.encode(value: any)→string

Encodes a table, string, number, boolean or `nil` as YAML text. The text ends with a line break. Throws `Failed to encode YAML` for functions and other values YAML cannot hold, and for tables that contain themselves.

Parameters

value any
Value to encode, usually a table

Returns

string The YAML text
Yaml.write(fileName: string, value: any)→self

Encodes a value like `Yaml.encode` and writes it to a file, replacing the file if it exists and creating missing directories.

Parameters

fileName string
YAML file to write, relative to the workspace
value any
Value to encode, usually a table

Returns

self chainable The library itself, so calls can be chained.