[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Reading a conf file
- From: steve donovan <steve.j.donovan@...>
- Date: Thu, 29 Sep 2016 09:58:23 +0200
On Thu, Sep 29, 2016 at 7:19 AM, Russell Haley <russ.haley@gmail.com> wrote:
> About the saving of values: yes, it is important not to molest the
> original file. I would like to be able to work with conf files in
> FreeBSD lik rc.conf and leave them intact.
Ah, that suggests a simple solution:
(1) read all the lines into an array
local f, e = io.open(file)
-- check that e!
local lines = {}
for line in f:lines() do
table.insert(lines,line)
end
f:close()
(2) process only non-blank or lines not starting with #
local values = {}
local value_lines = {}
for i,line in ipairs(lines) do
if not (line:match '^%s*$' or line:match '^#') then
local var,val = line:match('^([^=]+)=(.+)')
values[var] = val
value_lines[var] = i
end
end
The values table is what you need. Updating a var is like so
(3)
lines[value_lines[var]] = var..'='..new_value
and then write out
local f,e = io.open(file,'w');
for i,line in ipairs(lines) do
f:write(line,'\n')
end
f:close()