-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoml.lua
66 lines (61 loc) · 1.47 KB
/
toml.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
local Toml = {}
function Toml:new()
local instance = {}
setmetatable(instance, self)
self.__index = self
return instance
end
local function trim(s)
return s:match("^%s*(.-)%s*$")
end
function Toml:parseKV(line)
local k, v = line:match("([^=]+)=([^#]+)")
if k and v then
k = trim(k)
v = trim(v)
if v:match('^"') then
v = v:sub(2, -2)
elseif v == "true" then
v = true
elseif v == "false" then
v = false
elseif tonumber(v) then
v = tonumber(v)
end
return k, v
end
return nil
end
-- TODO full toml support https://toml.io/en/v1.0.0
function Toml:parse(filepath)
local file = io.open(filepath, "r")
if not file then
error("could not read file")
end
local toml = {}
local section = nil
for line in file:lines() do
line = trim(line:match("^[^#]*"))
if line == "" then
goto continue
end
local sectionName = line:match("^%[([%w_]+)%]$")
if sectionName then
section = sectionName
toml[section] = toml[section] or {}
else
local k, v = self:parseKV(line)
if k and v then
if section then
toml[section][k] = v
else
toml[k] = v
end
end
end
::continue::
end
file:close()
return toml
end
return Toml