lz4compress
Compresses a string using LZ4 compression.
function lz4compress(data: string): stringSynopsis
How it works
Compresses a string using the LZ4LZ4A high-speed lossless compression algorithm. Prioritizes speed over ratio (~4 GB/s decompression). Uses a hash table to find duplicate byte sequences and encodes them as offset+length back-references. algorithm, a high-speed lossless compression codec optimized for decompression speed.
LZ4 algorithm
LZ4LZ4A high-speed lossless compression algorithm. Prioritizes speed over ratio (~4 GB/s decompression). Uses a hash table to find duplicate byte sequences and encodes them as offset+length back-references. is a byte-oriented LZ77LZ77A dictionary-based compression algorithm that replaces repeated byte sequences with (offset, length) back-references to earlier occurrences in the data. LZ4, Zlib, and Snappy are all LZ77 variants. variant. It scans input with a hash tableHash tableA data structure that maps keys to values using a hash function. Luau tables use a hash table for string/mixed keys (the "node" part) alongside a separate contiguous array for integer keys. to find duplicate sequences:
For each position in input:
1. Hash the next 4 bytes → slot in hash table
2. If hash table[slot] matches current bytes:
→ Emit a MATCH token: (offset, length)
3. Else:
→ Emit a LITERAL token: (raw bytes)
4. Update hash table[slot] = current position
The output is a sequence of literal + match pairspairs()Returns an iterator that traverses all key-value pairs in a table (both array and hash parts). Order is not guaranteed for non-integer keys. Uses the next() function internally.. Each token encodes literal length (4 bits), match length (4 bits), and a 16-bit back-reference offset. Decompression is extremely fast (~4 GB/s) because it’s just memcpymemcpyA C standard library function that copies N bytes from a source memory address to a destination. Fundamental to LZ4 decompression and many VM operations. Very fast on modern CPUs due to SIMD optimization. operations — no Huffman decoding or arithmetic coding. Roblox uses LZ4 internally for asset streaming and replication.Usage
Compress / decompress
local text = "Hello, world! Hello, world! Goodbye, world!"
local comp = lz4compress(text)
print(#text, #comp) "cc">--> 43 34
print(lz4decompress(comp, #text)) "cc">--> Hello, world! Hello, world! Goodbye, world!Parameters
data string The uncompressed data.
Returns
string The LZ4-compressed bytes.