Search code examples
luaslurp

Lua one-liner to read entire file?


Is there a trick to slurp a file with just one line of code?

("to slup" = to read entire file into a string.)

Usually I do the following:

local f = io.open("/path/to/file")
local s = f:read("*a")
f:close()

But I wonder if there's a shorter way.

I know that we can do (in Lua 5.2) the following:

local s = io.lines("/path/to/file", "*a")()

But the file would stay open for a while until the garbage collector kicks in (and gets rid of the closure io.lines returns; I believe this closure knows to explicitly close the file, but this could happen only after the second invocation of it, when it knows EOF has been reached).

So, is there a one-line solution I'm missing?


Solution

  • There is no such function in the standard library, but you can just define it yourself:

    local function slurp(path)
        local f = io.open(path)
        local s = f:read("*a")
        f:close()
        return s
    end
    

    Alternatively there is such a function in Penlight.