[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Reading a conf file
- From: Russell Haley <russ.haley@...>
- Date: Thu, 29 Sep 2016 01:23:40 -0700
Thanks Steve. I just started playing with your ldoc tool. Very slick.
So late... need sleep...
Russ
Sent from my BlackBerry 10 smartphone on the Virgin Mobile network.
Original Message
From: steve donovan
Sent: Thursday, September 29, 2016 12:58 AM
To: Lua mailing list
Reply To: Lua mailing list
Subject: Re: Reading a conf file
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()