Sticky note
Only INFLATE/DEFLATE algorithms are supported by the
Zip
object.How to use ZIP archives with Luart
By Samir Tine, published on November 2022
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 compression module facilitates the creation of ZIP archive files. This module provides an abstraction of a ZIP file represented as a Zip object, with methods and properties for adding and extracting compressed files.
To use the Zip object, you must first require for the compression
module :
-- require the "compression" builtin module
local compression = require "compression"
-- the "compression" module contains the Zip object
print(compression.Zip)
To extract all content from an existing ZIP archive, you can use the Zip:extractall() method :
local compression = require "compression"
-- Create a Zip value to represent the ZIP file 'archive.zip'
local archive = compression.Zip("archive.zip")
-- extract and uncompress all the files in the current directory
archive:extractall()
To extract a specific archive entry, you can use the Zip:extract() method :
local compression = require "compression"
-- Open the Zip archive 'archive.zip' for reading (the default mode)
local archive = compression.Zip("archive.zip")
-- extract and uncompress the "data.bin" file in the specified directory
archive:extract("data.bin", "C:\\Extract\\Me\\Here")
A new empty ZIP archive can be created by providing a "write"
mode parameter in the Zip constructor. Files can then be added to the archive with the Zip:write() method:
local compression = require "compression"
-- Create a Zip value that represent a new empty ZIP file 'new_archive.zip'
local archive = compression.Zip("new_archive.zip", "write")
-- Write a new archive entry with the file "C:\\addme.txt"
archive:write("C:\\addme.txt")
You can add entire directory content with the same method:
-- Write new archive entries with the entire content of "C:\\folder_to_add\\"
archive:write("C:\\folder_to_add\\")
Zip object is iterable with the each() function, returning at every iteration the next entry name in the ZIP archive previously opened in "read"
mode:
local compression = require "compression"
-- Open the Zip archive 'archive.zip' for reading
local archive = compression.Zip("archive.zip")
-- Iterates over all archive entry names and prints them
for entry in each(archive) do
print(entry)
end
ZIP archive entries can also be extracted in-memory using the Zip:read() method :
local compression = require "compression"
-- Open the Zip archive 'archive.zip' for reading
local archive = compression.Zip("archive.zip")
-- Print the content of the ZIP archive entry "README.TXT"
print(archive:read("README.TXT"))