string.pack()

The string.pack() function in Lua is used to convert multiple values into a binary string using a specified format. This is useful for packing data into a format suitable for transmission or storage, such as when working with binary protocols or files.

Syntax

string.pack(format, ...)

Parameters

  • Name
    format
    Type
    string
    Description

    A string that specifies the format in which to pack the values. It defines how the subsequent values will be encoded.

  • Name
    ...
    Type
    any
    Description

    The values to be packed into a binary string, following the specified format.

Return Value

Returns the packed binary string.

Format Specification

The format string can contain various format codes that determine how the values are packed:

Format CodeDescription
bSigned byte (1 byte).
BUnsigned byte (1 byte).
hSigned short (2 bytes).
HUnsigned short (2 bytes).
lSigned long (4 bytes).
LUnsigned long (4 bytes).
fFloat (4 bytes).
dDouble (8 bytes).
sString (length-prefixed).
cCharacter (1 byte).
pPointer (4 bytes).
nNumber of bytes (to be written as unsigned long).

Examples

Example 1: Packing Basic Types

Pack various data types into a binary string.

Example 1

local packedData = string.pack("bhlf", -10, 20, 12345, 3.14)

print(packedData)  -- Output: A binary string representing the packed data

Example 2: Packing Strings

Pack a string along with a number.

Example 2

local name = "Lua"
local age = 5
local packedData = string.pack("s2l", name, age)  -- 's2' indicates the string length is 2

print(packedData)  -- Output: A binary string representing the packed data

Example 3: Unpacking the Data

To retrieve the values packed in a binary string, use string.unpack().

Example 3

local packedData = string.pack("bhlf", -10, 20, 12345, 3.14)
local unpackedValues = {string.unpack("bhlf", packedData)}

print(unpackedValues[1], unpackedValues[2], unpackedValues[3], unpackedValues[4])
-- Output: -10  20  12345  3.14

Use Cases

  • Network Communication: Packing data for transmission over a network.
  • File Storage: Storing structured data in a compact binary format.
  • Interfacing with C Libraries: Packing data to send to C functions that expect binary data.

See also

  • string.unpack(): Unpacks binary strings back into individual values based on a specified format.

Was this page helpful?

Table of Contents