Tutorial : How to use ZIP files with Luart
By Samir Tine, published on December 2021
ZIP archive files
ZIP is a file format that supports lossless compression. A lossless compression algorithm allows the original data to be perfectly reconstructed from the compressed data. A ZIP file contains one or more compressed files, making it an ideal way to reduce the size of large files and keep related files together.
The Zip Object
The zip module provides an abstraction of zip files represented as a Zip object. Only INFLATE/DEFLATE algorithms are supported. This module facilitates the creation of ZIP archive files and provides methods and properties for adding and extracting compressed files.
To use the Zip object, you must first require for the "zip" module :
-- require the builtin 'zip' module local zip = require "zip"
Extract files from a ZIP archive
To extract files from an existing ZIP archive, you can use the Zip:extractall() method :
local zip = require "zip" -- Create a Zip value to represent the ZIP file 'archive.zip' local archive = zip.Zip("archive.zip") -- extract and uncompress all the files in the current directory archive:extractall()
By default, if the mode parameter is not specified in the constructor, the Zip archive is open in "read" mode.
You can extract a specific entry with the Zip:extract() method :
-- extract the ZIP entry "extractme.bin" in the current directory archive:extract("extractme.bin")
A destination path can optionaly be provided :
-- extract the ZIP entry "data.bin" in the specified directory archive:extract("data.bin", "C:\\Extract\\Me\\Here")
Creating a ZIP archive
Providing a "write" mode parameter in the Zip constructor creates a new empty ZIP archive. Files can then be added to the archive with the Zip:write() method:
local Zip = require "zip" -- Create a Zip value in "write" mode to represent the ZIP file 'new.zip' local archive = zip.Zip("new.zip", "write") -- add a file to this archive archive:write("C:\\addme.txt"))
You can recursively add entire directories too :
Iterating over files in a ZIP archive
local zip = require "zip" -- Create a Zip value to represent the ZIP file 'archive.zip' local archive = zip.Zip("archive.zip") -- Iterate over each ZIP archive entries and extract it for entry in each(archive) do print("Extracting '"..entry.."'") archive:extract(entry) end
Reading ZIP archive entries in memory
ZIP archive entries can also be extracted in-memory using the Zip:read() method :
local zip = require "zip" -- Create a Zip value to represent the ZIP file 'archive.zip' local archive = zip.Zip("archive.zip") -- print the content of the ZIP archive entry 'README.TXT' print(archive:read("README.TXT"))
As you can see, the zip module provides an easy way to manage ZIP archives out of the box from Luart.