Data formats · real, tested code

Parse an INI Config File in Larzscript

Read a classic `[section]` / `key = value` config file into a nested dict.

No dedicated package for INI in the stack yet - a short hand-written parser (skip comments and blank lines, track the current section header, split each `key = value` line once) covers the common real-world subset.

Code

fn parse_ini(text) {
  let sections = {"": {}}
  let current = ""
  for raw_line in text.split("\n") {
    let line = raw_line.strip()
    if len(line) == 0 or line.starts_with(";") or line.starts_with("#") { continue }
    if line.starts_with("[") and line.ends_with("]") {
      current = line[1:len(line)-1]
      sections[current] = {}
      continue
    }
    let eq = line.find("=")
    if eq < 0 { continue }
    let key = line[0:eq].strip()
    let value = line[eq+1:].strip()
    sections[current][key] = value
  }
  return sections
}

let ini_text = "[server]\nhost = 0.0.0.0\nport = 8080\n\n[database]\nname = larzbank\ntimeout = 30\n"
let cfg = parse_ini(ini_text)
print(cfg["server"]["host"], cfg["server"]["port"])
print(cfg["database"]["name"], cfg["database"]["timeout"])
Output
0.0.0.0 8080
larzbank 30