lua-users home
lua-l archive

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


Hi there,

I'm trying to read and write to a conf file (i.e. each line is an
item, and key/value pair is separated by '='). I found that penlight
has an excellent parser, but it seems a little heavy importing that
whole thing  to parse character separated lines. I found a little lua
conf reader after that. I don't remember where I found this (lua
wiki?) but it sort of works:

local function ReadConf(filePath, debug)
    local conf = {}
    local fp = io.open(filePath, "r")
    if fp then
        conf["conf_file_path"] = filePath
        for line in fp:lines() do
            line = line:match("%s*(.+)")
            if line and line:sub(1, 1) ~= "#" and line:sub(1, 1) ~= ";" then
                local option = line:match("%S+"):lower()
                local value = line:match("%S*%s*(.*)")

                if not value then
                    conf[option] = false
                else
                    if not value:find(",") then
                        conf[option] = value
                    else
                        value = value .. ","
                        conf[option] = {}
                        for entry in value:gmatch("%s*(.-),") do
                            conf[option][#conf[option] + 1] = entry
                        end
                    end
                end
            end
        end
        fp:close()
    else
        --Should do something if the file doesn't exist
    end

    if debug == true then
        for i,v in pairs(conf) do
            print(i,v)
        end
    end

    return conf
end

So this parses SPACE separated lines. I'm not familiar enough with
line matching patterns or lpeg to be effective (seriously. every time
I've tried to 'fix' a reg-ex in C# I wind up breaking it beyond
repair). While these are both things I desperately want to learn, I'm
trying to get a working prototype of my software together and stopping
to learn lpeg is not where I want to be at this time(but I promise to
do it!).

I've also considered just serializing/deserializing lua tables, but at
some point I have to support reading and changing standard conf files
(and eventually wpa_supplication too).

Any feedback would be dandy.

Thanks,

Russ