-
Notifications
You must be signed in to change notification settings - Fork 5
/
ini.lua
94 lines (79 loc) · 2.24 KB
/
ini.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
local ini = {
_NAME = "Ini",
_VERSION = "1.0.0",
_DESCRIPTION = "A simple ini parser",
_CREATOR = "GuglioIsStupid",
_LICENSE = [[
MIT LICENSE
]]
}
local function split(str, sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields + 1] = c end)
return fields
end
local function convert(str)
if tonumber(str) then
return tonumber(str)
elseif str:lower() == "true" then
return true
elseif str:lower() == "false" then
return false
else
return str
end
end
function ini.parse(ini)
-- is it a file or str
local str
if love.filesystem.getInfo(ini) then
str = love.filesystem.read(ini)
else
str = ini
end
-- assert str to see if its nil or nah
assert(str, "No ini file or string provided")
local lines = split(str, "\n")
local data = {}
local currentSection = nil
for _, line in ipairs(lines) do
local comment = string.match(line, "^%s*;(.*)")
if line ~= "" and not comment then
local sec = string.match(line, "^%s*%[(.*)%]")
if sec ~= nil then
currentSection = sec
data[currentSection] = {}
else
local name, value = string.match(line, "^%s*(.-)%s*=%s*(.-)%s*$")
if name and value then
data[currentSection][name] = convert(value)
end
end
end
end
return data
end
function ini.save(tab, fileName)
-- sort 0-Z
local newTab = {}
for k, _ in pairs(tab) do
table.insert(newTab, k)
end
table.sort(newTab, function(a, b) return a < b end)
local str = ""
for _, section in ipairs(newTab) do
str = str .. "[" .. section .. "]\n"
local newTab2 = {}
for k, _ in pairs(tab[section]) do
table.insert(newTab2, k)
end
table.sort(newTab2, function(a, b) return a < b end)
for _, name in ipairs(newTab2) do
str = str .. name .. " = " .. tostring(tab[section][name]) .. "\n"
end
str = str .. "\n"
end
love.filesystem.write(fileName, str)
end
return ini