Lua
Lua
Compress Text from StringBuilder to Gzip (BinData Output)
See more Gzip Examples
This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.
The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.
This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- This example demonstrates how to compress text contained in a StringBuilder
-- into Gzip format, storing the compressed result in a BinData object.
local gzip = chilkat.Gzip.new()
local sb = chilkat.StringBuilder.new()
local bd = chilkat.BinData.new()
-- Add some text to the StringBuilder:
sb:append("The quick brown fox jumps over the lazy dog.")
-- Compress the text using UTF-8 encoding:
local success = gzip:compress_sb(sb, "utf-8", bd)
if not success then
print(gzip.last_error_text)
return
end
-- The BinData now contains the Gzip-compressed bytes.
print("Compression successful.")
print("Compressed size (bytes): " .. bd.num_bytes)
-- (Optional) Save to a .gz file:
success = bd:write_file("text.gz")
if not success then
print(bd.last_error_text)
return
end
print("Gzip file written to text.gz")