1
votes

I have got the following code:

function getusers(file)
    print (type(file))
    for line in file:lines() do
    user, value = string.match(file,"(UserName=)(.-)\n")
    print(value)
    end

    f:close()
    end

 f = assert(io.open('file2.ini', "r"))
 t = f:read("*all")
 getusers(t)

The return of:

print(type(file))

is type string. Lua returns me the error code:

lua: reader.lua:3: attempt to call method 'lines' (a nil value)

I don't know how to fix this problem. If I just use the lines between the for and the end (the lines in the for loop) it works great.

2

2 Answers

1
votes

f is a file handler, while t is a string that contains the content. You are trying to call io.lines, so it should be a file handler. In fact, you don't need t at all.

function getusers(file)
    print(type(file))
    for line in file:lines() do
        user, value = string.match(line,"(UserName=)(.*)")
        print(value)
    end

    f:close()
end

f = assert(io.open('t.txt', "r"))
getusers(f)

I've also modified the pattern to (UserName=)(.*) because now you are matching each line, not the whole file.

0
votes

I don't know if this is the smartest way, but now I use:

function getusers(file)
for line in file:lines() do
    user, value = string.match(line,"(UserName=)(.*)")
    if value ~= nil then
        print(value)
    end 
end

f:close()
end

f = assert(io.open('file2.ini', "r"))
getusers(f)

As you may see, I check the value of 'value' before printing it.