Search code examples
fileluaiofopenfclose

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


Solution

  • 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.