sibvic
sibvic

Reputation: 1662

Does io.lines(filename) closed the file when an error is happened?

What will happen with a file handle opened via io.lines if something bad happen inside the loop? The documentation says that the file will be automatically closed when the end of file is reached and says nothing for the exceptional cases (something like accesing a nil value in dosomething().

for line in io.lines("myfile.txt") do
    dosomething(line);
end

Does anybody know how the lua will handle the situation like this?

Upvotes: 2

Views: 546

Answers (1)

catwell
catwell

Reputation: 7020

The file will be closed when the object referencing it is garbage collected eventually.

If you are on a Unix system you can try that with the following program:

local f = function()
    for line in io.lines("myfile.txt") do
        print("1")
        io.read()
        error(line)
    end
end

pcall(f)

print("2")
io.read()

collectgarbage("collect")

print("3")
io.read()

If you run lsof at step 1 you will see the file open. At step 2, it will most probably still be open. At step 3 it won' be open anymore.

Upvotes: 3

Related Questions