mirror of
https://github.com/bartbes/inifile.git
synced 2024-11-15 23:54:23 +00:00
Add multiple-backend support for inifile, adding a memory backend
This commit is contained in:
parent
23453a30ff
commit
e886b00dda
@ -28,21 +28,32 @@
|
|||||||
|
|
||||||
inifile = {}
|
inifile = {}
|
||||||
|
|
||||||
local lines
|
local defaultBackend = "io"
|
||||||
local write
|
|
||||||
|
local backends = {
|
||||||
|
io = {
|
||||||
|
lines = function(name) return assert(io.open(name)):lines() end,
|
||||||
|
write = function(name, contents) assert(io.open(name, "w")):write(contents) end,
|
||||||
|
},
|
||||||
|
memory = {
|
||||||
|
lines = function(text) return text:gmatch("([^\r\n]+)\r?\n") end,
|
||||||
|
write = function(name, contents) return contents end,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
if love then
|
if love then
|
||||||
lines = love.filesystem.lines
|
backends.love = {
|
||||||
write = love.filesystem.write
|
lines = love.filesystem.lines,
|
||||||
else
|
write = function(name, contents) love.filesystem.write(name, contents) end,
|
||||||
lines = function(name) return assert(io.open(name)):lines() end
|
}
|
||||||
write = function(name, contents) return assert(io.open(name, "w")):write(contents) end
|
defaultBackend = "love"
|
||||||
end
|
end
|
||||||
|
|
||||||
function inifile.parse(name)
|
function inifile.parse(name, backend)
|
||||||
|
backend = backend or defaultBackend
|
||||||
local t = {}
|
local t = {}
|
||||||
local section
|
local section
|
||||||
for line in lines(name) do
|
for line in backends[backend].lines(name) do
|
||||||
local s = line:match("^%[([^%]]+)%]$")
|
local s = line:match("^%[([^%]]+)%]$")
|
||||||
if s then
|
if s then
|
||||||
section = s
|
section = s
|
||||||
@ -59,7 +70,8 @@ function inifile.parse(name)
|
|||||||
return t
|
return t
|
||||||
end
|
end
|
||||||
|
|
||||||
function inifile.save(name, t)
|
function inifile.save(name, t, backend)
|
||||||
|
backend = backend or defaultBackend
|
||||||
local contents = ""
|
local contents = ""
|
||||||
for section, s in pairs(t) do
|
for section, s in pairs(t) do
|
||||||
local sec = ("[%s]\n"):format(section)
|
local sec = ("[%s]\n"):format(section)
|
||||||
@ -68,7 +80,7 @@ function inifile.save(name, t)
|
|||||||
end
|
end
|
||||||
contents = contents .. sec .. "\n"
|
contents = contents .. sec .. "\n"
|
||||||
end
|
end
|
||||||
write(name, contents)
|
return backends[backend].write(name, contents)
|
||||||
end
|
end
|
||||||
|
|
||||||
return inifile
|
return inifile
|
||||||
|
Loading…
Reference in New Issue
Block a user