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

--Size of three integers
local size = string.packsize("iii")
engine.print(size) --12
--Size of a double
local size = string.packsize("d")
engine.print(size) --8
--Size of fixed string
local size = string.packsize("c10")
engine.print(size) --10
--Size of multiple types
local size = string.packsize("ifd")
engine.print(size) --16
--Size with little endian specifier
local size = string.packsize("<I4")
engine.print(size) --4
--Size of byte
local size = string.packsize("b")
engine.print(size) --1
--Size of short
local size = string.packsize("h")
engine.print(size) --2
--Size of long
local size = string.packsize("l")
engine.print(size) --8
--Size with padding
local size = string.packsize("ixxi")
engine.print(size) --12
--Size comparison
engine.print("i4:", string.packsize("i4")) --4
engine.print("i8:", string.packsize("i8")) --8
--Calculate buffer size needed
local fmt = "i4i4f"
local bufferSize = string.packsize(fmt)
engine.print("Need", bufferSize, "bytes") --Need 12 bytes
--Multiple fixed strings
local size = string.packsize("c5c5c5")
engine.print(size) --15
--Verify pack size
local fmt = "ifd"
local size = string.packsize(fmt)
local packed = string.pack(fmt, 1, 2.5, 3.14)
engine.print(#packed == size) --true
--Pre-allocate file buffer
local recordFormat = "c32i4i4"
local recordSize = string.packsize(recordFormat)
engine.print("Each record:", recordSize, "bytes")
--Network protocol size calculation
local headerFormat = ">I2I2I4"
local headerSize = string.packsize(headerFormat)
engine.print("Header size:", headerSize) --8

On this page