Vital.sandbox
String

string.pack

Shared

Packs values into a binary string according to a format


Syntax

local binary = string.pack(format, ...)

Parameters

TypeNameDescription
stringformatFormat string containing specifiers describing how to pack the values
Refer Specifiers section
......Values to pack

Returns

TypeNameDescription
stringbinaryBinary string containing the packed values

Specifiers

SpecifierDescription
bSigned byte (char)
BUnsigned byte (unsigned char)
hSigned short
HUnsigned short
lSigned long
LUnsigned long
jlua_Integer
Jlua_Unsigned
Tsize_t
i[n]Signed int with n bytes
I[n]Unsigned int with n bytes
fFloat
dDouble
nLua number
c[n]Fixed-size string of n bytes
zZero-terminated string
s[n]String preceded by length
xOne byte of padding
<Set little endian
>Set big endian
=Set native endian

Examples

Pack three integers into a binary string
local packed = string.pack("iii", 10, 20, 30)

engine.print("info", #packed) --12
Pack a fixed-size string
local packed = string.pack("c5", "hello")

engine.print("info", #packed) --5
Pack a zero-terminated string
local packed = string.pack("z", "world")

engine.print("info", #packed) --6
Pack mixed types into one binary string
local packed = string.pack("ifd", 42, 3.14, 2.718)
Pack a value in little endian byte order
local packed = string.pack("<I4", 0x12345678)
Pack a value in big endian byte order
local packed = string.pack(">I4", 0x12345678)
Pack raw bytes as a string
local packed = string.pack("BBB", 65, 66, 67)

engine.print("info", packed) --'ABC'
Pack values with padding bytes
local packed = string.pack("ixxi", 1, 2)
Pack an unsigned short
local packed = string.pack("H", 1000)
Pack a double precision float
local packed = string.pack("d", math.pi)
Pack a string with a length prefix
local packed = string.pack("s1", "hello")
Pack multiple zero-terminated strings
local packed = string.pack("zz", "first", "second")
Combine different types in one pack call
local packed = string.pack("i4f", 100, 1.5)
Pack a value in network byte order
local packed = string.pack(">I2", 0xABCD)
Pack struct-like player data
local packed = string.pack("c10i4f", "PlayerName", 100, 99.5)
Pack a boolean as a byte
local packed = string.pack("b", (true and 1) or 0)

On this page