Parsing single level yaml files into a Lua table

Given a yaml-like file containing key-value pairs like this:

1
2
3
key1: value1
key2: value2
key3: value3

The following function will load it and return the data as a Lua table.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function read_yaml_file(filename)
  local file = io.open(filename, "r")
  if not file then
    return nil, "Failed to open file: " .. filename
  end

  local data = {}
  for line in file:lines() do
    local key, value = line:match("(%w+):%s*(.+)")
    if key and value then
      data[key] = value
    end
  end

  file:close()
  return data
end
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy