Library for Converting Data to and from C Structs for Lua 5.1

(download)

This library offers basic facilities to convert Lua values to and from C structs. Its main functions are struct.pack, which packs multiple Lua values into a struct-like string; and struct.unpack, which unpacks multiple Lua values from a given struct-like string.

The fist argument to both functions is a format string, which describes the layout of the structure. The format string is a sequence of conversion elements, which respect the current endianess and the current alignment requirements. Initially, the current endianess is the machine's native endianness and the current alignment requirement is 1 (meaning no alignment at all). We can change these settings with appropriate directives in the format string.

The elements in the format string are as follows:

Lua API

All functions are registered inside a table struct. ul>

  • struct.pack (fmt, d1, d2, ...)

    Returns a string containing the values d1, d2, etc. packed according to the format string fmt.

  • struct.unpack (fmt, s, [i])

    Returns the values packed in string s according to the format string fmt. An optional i marks where in s to start reading (default is 1). After the read values, this function also returns the index in s where it stopped reading, which is also where you should start to read the rest of the string.

  • struct.size (fmt)

    Returns the size of a string formatted according to the format string fmt. For obvious reasons, the format string cannot contain neither the option s nor the option c0.

    Installing

    To install, simply compile the file struct.c as a dynamic library. In Linux you can use the following command:

    > gcc -Wall -O2 -shared -o struct.so struct.c
    
    In Mac, you should define the environment variable MACOSX_DEPLOYMENT_TARGET as 10.3 and then write
    > gcc -bundle -undefined dynamic_lookup -Wall -O2 -o struct.so struct.c
    

    In Windows, you must generate a DLL exporting the single symbol luaopen_struct.

    Examples

    Tests

    File teststruct contains a full test script for this package. It is also a good source of examples.

    $Id: struct.html,v 1.4 2008/04/18 20:10:24 roberto Exp $