Comprehensive Windows framework to develop in Lua

Tutorial : How to use ZIP files with Luart

By Samir Tine, published on December 2021

Luart provides a builtin zip module to work with compressed files in ZIP format, without any additional dependencies. Here you can read a short tutorial on using ZIP archives with it.

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 ''
local archive = zip.Zip("")

-- extract and uncompress all the files in the current directory

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 

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 ''
local archive = zip.Zip("", "write")

-- add a file to this archive

You can recursively add entire directories too :


Iterating over files in a ZIP archive

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 zip = require "zip"

-- Create a Zip value to represent the ZIP file ''
local archive = zip.Zip("")

-- Iterate over each ZIP archive entries and extract it
for entry in each(archive) do
    print("Extracting '"..entry.."'")

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 ''
local archive = zip.Zip("")

-- print the content of the ZIP archive entry 'README.TXT'

As you can see, the zip module provides an easy way to manage ZIP archives out of the box from Luart.