Data Compression With luau-zlib

For those who’d prefer, a full version of the article is available on Medium

luau-zlib is a Luau library for data compression. It works on Roblox, Lune, or other Luau environment. It uses the zlib compression format, which is compatible with standard zlib implementations used across many programming languages.

Basic Usage

The library exposes four functions, which takes a string and returns a string. These functions return nil if they fail.

  • compressZlib and decompressZlib
  • compressDeflate and decompressDeflate

Here is a simple example of how you can compress data:

local zlib = require("@pkg/luau-zlib")

local data = "some string data to compress"

local compressed = zlib.compressZlib(data)
local decompressed = zlib.decompressZlib(compressed)

assert(decompressed == data)

The compression functions accept an optional configuration object that lets you control the compression level:

local compressed = zlib.compressZlib(data, {
    level = 5, -- 0 to 9
})

For more information, take a look at the README on GitHub.

Usage of Zlib vs Deflate

Zlib wraps the compressed data with a header and a checksum. Use this when you need to decompress something from outside of Luau, or compress in Luau for outside. The value will be readable in Python, Node, etc.

Deflate is raw compression: no header and no checksum for a smaller output. It’s an alternative to save as much bytes as possible. Unless you know what you’re doing, you should probably use the zlib functions.

Installation

The project is hosted on GitHub. You can grab a Roblox model file attached to the latest release:

  1. Navigate to the GitHub releases
  2. Scroll to the Assets section and download the zlib.rbxm (Roblox model file)
  3. Drag the file into Roblox Studio

In the release, you can also find a bundled Luau file zlib.luau, which is all the library compiled in a single file using darklua.

The project is also published on the npm registry. You can add luau-zlib to your project dependencies with:

yarn add luau-zlib
# or
npm install luau-zlib

Useful Links

A few other articles I wrote:

3 Likes