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 Code | Description |
---|---|
b | Signed byte (1 byte). |
B | Unsigned byte (1 byte). |
h | Signed short (2 bytes). |
H | Unsigned short (2 bytes). |
l | Signed long (4 bytes). |
L | Unsigned long (4 bytes). |
f | Float (4 bytes). |
d | Double (8 bytes). |
s | String (length-prefixed). |
c | Character (1 byte). |
p | Pointer (4 bytes). |
n | Number 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.