util.string.packsize

Shared

Retrieves the size of a string resulting from `util.string.pack`


Syntax

local size = util.string.packsize(
    format
)

Parameters

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

Returns

TypeNameDescription
intsizeThe size in bytes of the packed string that would result from util.string.pack

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

Get the size of three packed integers
local size = util.string.packsize("iii")

core.engine.print("info", size) -- 12
Get the size of a packed double
local size = util.string.packsize("d")

core.engine.print("info", size) -- 8
Get the size of a fixed-length string
local size = util.string.packsize("c10")

core.engine.print("info", size) -- 10
Get the size of multiple packed types
local size = util.string.packsize("ifd")

core.engine.print("info", size) -- 16
Get the size with a little endian specifier
local size = util.string.packsize("<I4")

core.engine.print("info", size) -- 4
Get the size of a packed byte
local size = util.string.packsize("b")

core.engine.print("info", size) -- 1
Get the size of a packed short
local size = util.string.packsize("h")

core.engine.print("info", size) -- 2
Get the size of a packed long
local size = util.string.packsize("l")

core.engine.print("info", size) -- 8
Get the size of a format with padding
local size = util.string.packsize("ixxi")

core.engine.print("info", size) -- 12
Compare sizes of different integer widths
core.engine.print("info", "i4:", util.string.packsize("i4")) -- 4
core.engine.print("info", "i8:", util.string.packsize("i8")) -- 8
Calculate the buffer size needed for a format
local fmt = "i4i4f"
local bufferSize = util.string.packsize(fmt)

core.engine.print("info", "Need", bufferSize, "bytes") -- 'Need 12 bytes'
Get the size of multiple fixed strings
local size = util.string.packsize("c5c5c5")

core.engine.print("info", size) -- 15
Verify packsize matches the actual packed length
local fmt = "ifd"
local size = util.string.packsize(fmt)
local packed = util.string.pack(fmt, 1, 2.5, 3.14)

core.engine.print("info", #packed == size) -- true
Pre-calculate record size for file buffers
local recordFormat = "c32i4i4"
local recordSize = util.string.packsize(recordFormat)

core.engine.print("info", "Each record:", recordSize, "bytes")
Calculate a network protocol header size
local headerFormat = ">I2I2I4"
local headerSize = util.string.packsize(headerFormat)

core.engine.print("info", "Header size:", headerSize) -- 8

On this page