Created
August 18, 2018 15:46
-
-
Save DaeZak/dc90b3a49d22c3948c8bd060555245a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local iniparse = {} | |
local trim = function(str) | |
return string.gsub(str, "^%s*(.-)%s*$", "%1") | |
end | |
local strip_comments = function(str) | |
return string.gsub(str, "^(.-)%s*([;#].*)$", "%1") | |
end | |
iniparse.config = function(cfg) | |
iniparse.opts = { | |
trim = cfg.trim == nil and true or cfg.trim, | |
lc = cfg.lc == nil and true or cfg.lc | |
} | |
end | |
iniparse.load_file = function(fileName) | |
assert(type(fileName) == 'string', 'load_file given non-string arg') | |
local file = assert(io.open(fileName, 'r'), 'Error opening' .. fileName) | |
iniparse.parse(file:read('*all')) | |
end | |
iniparse.parse = function(data) | |
assert(type(data) == 'string', 'parse given non-string arg') | |
local rtable = {} | |
local lastSection = nil | |
for rawLine in data:gmatch("([^\n]*)\r?\n") do | |
local line = iniparse.opts.trim and trim(rawLine) or rawLine | |
line = iniparse.opts.lc and line:lower() or line | |
line = strip_comments(line) | |
if line:len() > 0 then | |
local section = string.match(line,"^%[([%w%s%p]*)%]") | |
if section ~= nil then | |
if rtable[section] ~= nil then | |
error('Invalid ini - duplicate section ' .. section) | |
end | |
rtable[section] = {} | |
lastSection = section | |
else | |
k,v = string.match(line,"^([%w%s%p]*)=([%w%s%p]*)$") | |
k = iniparse.opts.trim and trim(k) or k | |
v = iniparse.opts.trim and trim(v) or v | |
if lastSection == nil then | |
rtable[k] = v | |
else | |
rtable[lastSection][k] = v | |
end | |
end | |
end | |
end | |
return rtable | |
end | |
iniparse.config{} | |
return iniparse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment