Codectionary / Developer documentation / Lua

Lua binary packing

Lua 5.3+ string.pack and string.unpack encode binary layouts with explicit endianness and widths. Use Luau buffers when targeting Luau rather than assuming these Lua APIs exist.

Syntax

local bytes = string.pack("<I2I2", first, second)

Examples

Lua binary packing

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local bytes = string.pack("<I2I2", 513, 7)
local id, count, nextPosition = string.unpack("<I2I2", bytes)
print(#bytes)
print(id, count, nextPosition)
  1. Output: 4, then 513, 7 and 5 separated by tabs. Two unsigned 16-bit little-endian fields consume four bytes; 5 is the next one-based position.

Best practices

  • Document widths and byte order and validate lengths before decoding. Binary strings may contain embedded zero bytes.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading