string.unpack()
The string.unpack()
function in Lua is used to extract values from a binary string based on a specified format. This function is particularly useful for decoding data that has been packed using the string.pack()
function, allowing you to retrieve the original values in their respective types.
Syntax
string.unpack(fmt, s, pos)
Parameters
- Name
fmt
- Type
- string
- Description
The format string that specifies how to interpret the binary data in the input string.
- Name
s
- Type
- string
- Description
The binary string from which values will be extracted.
- Name
pos
- Type
- number
- Description
The starting position in the string to begin unpacking values. Defaults to 1.
Return Value
Returns the unpacked values from the binary string according to the specified format. If the format string is invalid or does not match the data, the return values may be undefined.
Examples
Example 1: Basic Unpacking
Unpacking a single integer from a binary string.
Example 1
local packedData = string.pack("i", 42)
local value = string.unpack("i", packedData)
print(value) -- Output: 42
Example 2: Unpacking Multiple Values
Unpacking multiple values from a binary string.
Example 2
local packedData = string.pack("i4s", 12345, "Lua")
local num, str = string.unpack("i4s", packedData)
print(num) -- Output: 12345
print(str) -- Output: Lua
Example 3: Specifying a Position
Unpacking from a specific position in the binary string.
Example 3
local packedData = string.pack("i2s", 100, "Code")
local num, str = string.unpack("i2s", packedData, 1)
print(num) -- Output: 100
print(str) -- Output: Code
Example 4: Handling Invalid Format
Demonstrate behavior when using an invalid format.
Example 4
local packedData = string.pack("i", 100)
local success, value = pcall(string.unpack, "z", packedData)
print(success) -- Output: false
print(value) -- Output: (error message)
Use Cases
- Data Decoding: Retrieving values from packed binary data for further processing.
- Network Communication: Unpacking data received over a network that has been formatted for transmission.
See also
string.pack()
: The function used to create packed binary data that can be unpacked usingstring.unpack()
.