lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Sep 28, 2016 at 3:55 PM, Valentin <vsl@dasdeck.com> wrote:
> 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

Okay all you smarty pants (tee hee)! I need to be able to replace the
value of a line item in said conf files. This was my terrible attempt
some moons ago:

local function SetItem(table, item, value)
--Read in the file and look for the "Item value
local conf = file.read(table.conf_file_path)
local i, j = conf:find(item)
if i then --if item is found
--replace item=<anything> with item=value
-- THIS SUBSTITUTION DOESN"T WORK PROPERLY IT ONLY FINDS LINEFEED not
the end of string
conf = conf:gsub(item .. "=.-[%\n|$]", item .. "=" .. value .. "\n")
else --item wasn't found
if conf:sub(#conf, 1) == "\n" then
conf = conf .. item .. "=" .. value
else
conf = conf .. "\n" .. item .. "=" .. value
end
end
print(conf)
file.write(ConfFileName, conf)
end

Any ideas are welcome. I haven't gotten to look at Jeromes code yet
and the answer could be in there...

Seriously though, thanks everyone for the fantastic feedback. I wish I
had joined this mailing list six months ago! Nothing like learning a
new language to make you feel like a freshman again...

Russ