Add multiple-backend support for inifile, adding a memory backend

This commit is contained in:
Bart van Strien 2012-08-30 02:23:45 +02:00
parent 23453a30ff
commit e886b00dda

View File

@ -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