YAML Encoding
YAML Encoding
Section titled “YAML Encoding”Parse YAML documents into Lua tables and serialize Lua values to YAML strings.
Loading
Section titled “Loading”local yaml = require("yaml")Encoding
Section titled “Encoding”Encode Value
Section titled “Encode Value”Encodes a Lua table to YAML format.
-- Simple key-valuelocal config = { name = "myapp", port = 8080, debug = true}local out = yaml.encode(config)-- name: myapp-- port: 8080-- debug: true
-- Arrays become YAML listslocal items = {"apple", "banana", "cherry"}yaml.encode(items)-- - apple-- - banana-- - cherry
-- Nested structureslocal server = { http = { address = ":8080", timeout = "30s" }, database = { host = "localhost", port = 5432 }}yaml.encode(server)| Parameter | Type | Description |
|---|---|---|
data | table | Lua table to encode |
options | table? | Optional encoding options |
Options
Section titled “Options”| Field | Type | Description |
|---|---|---|
field_order | string[] | Custom field ordering - fields appear in this order |
sort_unordered | boolean | Sort fields not in field_order alphabetically |
-- Control field order in outputlocal entry = { zebra = 1, alpha = 2, name = "test", kind = "demo"}
-- Fields appear in specified order, remaining sorted alphabeticallylocal result = yaml.encode(entry, { field_order = {"name", "kind"}, sort_unordered = true})-- name: test-- kind: demo-- alpha: 2-- zebra: 1
-- Just sort all fields alphabeticallyyaml.encode(entry, {sort_unordered = true})-- alpha: 2-- kind: demo-- name: test-- zebra: 1Returns: string, error
Decoding
Section titled “Decoding”Decode String
Section titled “Decode String”Parses a YAML string into a Lua table.
-- Parse configurationlocal config, err = yaml.decode([[server: host: localhost port: 8080features: - auth - logging - metrics]])if err then return nil, errend
print(config.server.host) -- "localhost"print(config.server.port) -- 8080print(config.features[1]) -- "auth"
-- Parse from file contentlocal content = fs.read("config.yaml")local settings, err = yaml.decode(content)if err then return nil, errors.wrap(err, "invalid config file")end
-- Handle mixed typeslocal data = yaml.decode([[name: testcount: 42ratio: 3.14enabled: truetags: - lua - wippy]])print(type(data.count)) -- "number"print(type(data.enabled)) -- "boolean"print(type(data.tags)) -- "table"| Parameter | Type | Description |
|---|---|---|
data | string | YAML string to parse |
Returns: any, error - Returns table, array, string, number, or boolean depending on YAML content
Errors
Section titled “Errors”| Condition | Kind | Retryable |
|---|---|---|
| Input not a table (encode) | errors.INVALID | no |
| Input not a string (decode) | errors.INVALID | no |
| Empty string (decode) | errors.INVALID | no |
| Invalid YAML syntax | errors.INTERNAL | no |
See Error Handling for working with errors.