views:

173

answers:

1

How do I extract files using Lua?

Update: I now have the following code but it crashes every time it reaches the end of the function, but it successfully extracts all the files and puts them in the right location.

require "zip"

function ExtractZipAndCopyFiles(zipPath, zipFilename, destinationPath)
    local zfile, err = zip.open(zipPath .. zipFilename)

    -- iterate through each file insize the zip file
    for file in zfile:files() do
        local currFile, err = zfile:open(file.filename)
        local currFileContents = currFile:read("*a") -- read entire contents of current file
        local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

        -- write current file inside zip to a file outside zip
        if(hBinaryOutput)then
            hBinaryOutput:write(currFileContents)
            hBinaryOutput:close()
        end
    end

    zfile:close()
end
-- call the function
ExtractZipAndCopyFiles("C:\\Users\\bhannan\\Desktop\\LUA\\", "example.zip", "C:\\Users\\bhannan\\Desktop\\ZipExtractionOutput\\")

Why does it crash every time it reaches the end?

+3  A: 

Short Answer:

LuaZip is a lightweight Lua extension library used to read files stored inside zip files. The API is very similar to the standard Lua I/O library API.

Use LuaZip to read files from the archive and then write them to the filesystem using the Lua io module. If you require filesystem operations not supported by ANSI C, then take a look at LuaFileSystem. LuaFileSystem is a Lua library developed to complement the set of functions related to file systems offered by the standard Lua distribution. LuaFileSystem offers a portable way to access the underlying directory structure and file attributes.


Further reading:

LAR is a virtual file system for Lua using ZIP compression.

If you need to read gzip streams or gzipped tar files then take a look at gzio. The Lua gzip file I/O module emulates the standard I/O module, but operates on compressed gzip format files.

Judge Maygarden
I don't believe this will work. I want to actually extract the files inside the zip, not just view the files inside the zip.
Brian T Hannan
Extraction is the process of reading from the archive and writing to the file system. Do you need instruction on writing to your file system? If so, please see the Lua `io` and `os` modules.
Judge Maygarden
So I would have to read and write each file? Maybe I'll be better off making a windows system call to unzip the files.
Brian T Hannan
That's fine if you are installing an archiver alongside your script. I'm unaware of a command line utility for extracting Zip files bundled with Windows.
Judge Maygarden
Alright, I gave in ... looks like writing to a file is easy. Then I can just open each file from the zip and write it out to wherever I want.
Brian T Hannan