Monsieur Pierre Doune
Monsieur Pierre Doune

Reputation: 747

Lua: Is File Closing Mandatory?

Let's say I want to store passwd content in a variable, just like this:

local passwd = io.open('/etc/passwd', 'r'):read('a') 

Is it ok that I didn't close the file after reading? Should I rewrite it like this:

local f = io.open('/etc/passwd', 'r')
local passwd = f:read('a')
f:close()

I know that first piece of code works, but I do not — if it can cause some hidden problems.

I'm using Lua 5.3

Upvotes: 2

Views: 4027

Answers (2)

Personage
Personage

Reputation: 484

A Lua FILE* is a resource handle similar to an std::ifstream or std::ofstream in C++. Resource handles are meant to automatically allocate and then deallocate resources--a fundamental concept in object-oriented programming.

Lua FILE*s have close functions in their metatables, which is what you are calling in your example with f:close(). This is to close them explicitly. But, in the OOP-style, they are closed implicitly using the __gc metamethod. Here is an example I quickly wrote to test this:

function myclose(self)
    io.close(self)
    io.stderr:write(string.format("File closed\n"))
    return
end

file = assert(io.open("input.txt", "r"))
debug.getmetatable(file)["__gc"] = myclose

In the last line, I change the value of __gc to myclose; thus, when this FILE* object's lifetime ends, myclose gets called instead of the default function. This means that "File closed" is printed to stderr when the script exits.

So, to get back to your original question, it is unnecessary to explicitly close Lua files.

Upvotes: 0

Lua will close files when the file object is garbage-collected - as Personage said in their answer.

However, that might not be soon. If you don't close files yourself, then:

  • If you keep opening files, you could run into the maximum number of open files before they get closed automatically.
  • On some platforms, other processes might not be able to open the file for writing, while you have it open for reading.
  • If you open a file for writing, data that you write might not actually be stored in the file until it gets closed.
  • Since garbage collection is related to memory usage, which has nothing to do with files, the file might not be closed for a long time if you don't allocate much memory.

Upvotes: 7

Related Questions