structModule
Binary codec for fixed C struct layouts.
Calling the module on a layout descriptor (as generated by autogen, e.g.require("linux.netlink").layout.nlmsghdr) derives a string.pack format
once and returns a codec exposing pack/unpack/size, so callers never
hand-write the byte layout.
Usage
local struct = require("struct")
local nlmsghdr = struct(require("linux.netlink").layout.nlmsghdr)
local bytes = nlmsghdr:pack(len, mtype, flags, seq, pid)
local len, mtype = nlmsghdr:unpack(bytes)
Class codec
| codec:fieldsize (name) | Returns the size in bytes of a named field. |
| codec:pack (...) | Serializes the field values (in offset order) into the struct’s bytes. |
| codec:unpack (buf[, pos]) | Deserializes the struct’s fields from a buffer. |
struct
| struct (layout) | Builds a codec from a layout descriptor. |
Class codec in detail
Codec a layout builds, packing its fields in native byte order. Its
size field holds the
struct’s size in bytes.
- codec:fieldsize (name)
-
Returns the size in bytes of a named field.
Parameters
- name string the field name.
Returns
-
integer or nil
the field size, or
nilif the layout has no such field. - codec:pack (...)
-
Serializes the field values (in offset order) into the struct’s bytes.
Parameters
- ... the field values
Returns
- codec:unpack (buf[, pos])
-
Deserializes the struct’s fields from a buffer.
Parameters
- buf string
- pos integer starting offset (1-based) (optional)
Returns
-
the field values in offset order, then the position past the struct
struct in detail
- struct (layout)
-
Builds a codec from a layout descriptor.
Parameters
- layout
table
{ size = bytes, fields = { {name, offset, size, signed}, ... } }
Returns
-
codec
a codec exposing
:pack,:unpack,:fieldsizeand asizefield.Raises
“struct: derived format does not match the layout size (overlapping fields?)” - layout
table