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

Read Next

I’m running an experiment for better content recommendations. These are the 3 posts that are most likely to be interesting for you:

Licensed under CC BY-NC-SA 4.0
All content is licensed under CC BY-NC-SA 4.0. Copying is an act of love - please copy!
More cool websites: Prev | Hotline Webring | Next
Built with Hugo
Theme Stack designed by Jimmy