Vital.sandbox
String

string.packsize

Shared

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


Syntax

local size = string.packsize(format)

Parameters

TypeNameDescription
stringformatFormat string - same format as used in string.pack

Returns

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

Examples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

On this page