[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Reading a conf file
- From: Valentin <vsl@...>
- Date: Thu, 29 Sep 2016 00:55:33 +0200
Sean Conner wrote:
[ snip ]
> You already have a parser available to you---Lua. If the config file is
> just what you said:
>
> a=series
> of=key
> value=pairs
>
> A small change:
>
> a='series'
> of='key'
> value='pairs'
> and_a_number=3
>
> and that can be read in as:
>
> CONF = {} -- your data will end up here
> f = loadfile("my-configfile.txt","t",CONF)
> f()
>
> print(CONF.a,CONF.and_a_number)
Based on the same idea, but without requiring to add quotes to the conf
file, here a simple function for reading such "INI-like" conf files into
a table. All table values will be strings, and have to be casted
manually to other types if needed.
function loadConfFile (fn)
local f = io.open(fn, 'r')
if f==nil then return {} end
local str = f:read('*a')..'\n'
f:close()
local res = 'return {'
for line in str:gmatch("(.-)[\r\n]") do
line = line:gsub('^%s*(.-)%s*$"', '%1') -- trim line
-- ignore empty lines and comments
if line~='' and line:sub(1,1)~='#' then
line = line:gsub("'", "\\'") -- escape all '
line = line:gsub("=%s*", "='", 1)
res = res..line.."',"
end
end
res = res..'}'
return loadstring(res)()
end
Usage:
======
-- contents of test.conf
a = 23
b=hello 'world'
# just a comment
c = hello world
-- /contents of test.conf
local config = loadConfFile('test.conf')
for k,v in pairs(conf) do
print(k, v)
end
--> a 23
--> c hello world
--> b hello 'world'
Valentin