Pekinese
Pekinese

Reputation: 177

reading special lines in lua

I am searching for the easiest way to read a string which is located in a file with a variable number of lines behind:

UserName=herecomesthestring

I thought about hardcoding a the linenumber, but this won't work, because in this file, the UserName can be more then once and the line numbers aren't the same (from user to user they may change).

Upvotes: 2

Views: 127

Answers (2)

Pekinese
Pekinese

Reputation: 177

I edited the function above a bit, now it works more or less, just need to edit the RegEx.

function getusers(file)
local list, close = {}
    local user, value = string.match(file,"(UserName=)(.*)")
    print(value)
    f:close()
end

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

  1. Read the file line-by-line
  2. Match the line and extract the username
  3. Put it in a list
function getusers(file)
    local list, close = {}
    if type(file) == "string" then
        file, close = io.open(file, "r"), true
    end
    for line in file:lines() do
        local user, value = line:match "^([^=]+)=([^\n]*)$"
        if user then -- Dropping mal-formed lines
            table.insert(list, user)
            list[user] = value -- Might be of interest too, so saving it
        end
    end
    if close then
        file:close()
    end
    return list
end

Call with either a file or a filename.

Upvotes: 1

Related Questions