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

原创 2012年03月21日 11:24:53

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


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:

  • "!n" flag to set the current alignment requirement to n (necessarily a power of 2); an absent n means the machine's native alignment.
  • ">" flag to set mode to big endian.
  • "<" flag to set mode to little endian.
  • " " (empty space) ignored.
  • "x" a padding zero byte with no corresponding Lua value.
  • "b" a signed char.
  • "B" an unsigned char.
  • "h" a signed short (native size).
  • "H" an unsigned short (native size).
  • "l" a signed long (native size).
  • "L" an unsigned long (native size).
  • "in" a signed integer with n bytes (where n must be a power of 2). An absent n means the native size of an int.
  • "In" like "in" but unsigned.
  • "f" a float (native size).
  • "d" a double (native size).
  • "s" a zero-terminated string.
  • "cn" a sequence of exactly n chars corresponding to a single Lua string. An absent n means 1. When packing, the given string must have at least n characters (extra characters are discarded).
  • "c0" this is like "cn", except that the n is given by other means: When packing, n is the length of the given string; when unpacking, n is the value of the previous unpacked value (which must be a number). In that case, this previous value is not returned.


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.


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.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.c

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


  • The code print(struct.size("i")) prints the size of a machine's native int.

  • To pack and unpack the structure

    struct Str {
      char b;
      int i[4];
    in Linux/gcc/Pentium (little-endian, maximum alignment of 4), you can use the string "<!4biiii".
  • If you need to code a structure with a large array, you may use string.rep to automatically generate part of the string format. For instance, for the structure

    struct Str {
      double x;
      int i[400];
    you may build the format string with the code "d"..string.rep("i", 400).
  • To pack a string with its length coded in its first byte, use the following code:

    x = struct.pack("Bc0", string.len(s), s)
    To unpack that string, do as follows:
    s = struct.unpack("Bc0", x)
    Notice that the length (read by the element "B") is not returned.
  • Suppose we have to decode a string s with an unknown number of doubles; the end is marked by a zero value. We can use the following code:

    local a = {}
    local i = 1         -- index where to read
    while true do
      local d
      d, i = struct.unpack("d", s, i)
      if d == 0 then break end
      table.insert(a, d)
  • To pack a string in a fixed-width field with 10 characters padded with blanks, do as follows:

    x = struct.pack("c10", s .. string.rep(" ", 10))


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


This package is distributed under the MIT license. See copyright notice at the end of file struct.c.

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

Lua struct teststruct
  • whitehack
  • whitehack
  • 2012年01月03日 18:03
  • 6676

【Programming In Lua (2E) 笔记】5:使用C++为Lua编写扩展库(macOS上两种动态库格式的坑)

  • elloop
  • elloop
  • 2016年08月31日 20:39
  • 1347


1 CAPI Lua与C可以有两种方式进行交互,一种是把LUA的功能作为库进行使用。另一种是在LUA中调用C库的功能,二者都可以通过CPAI的方式在LUA与C之间建立起桥梁。主要的数据结构是一个虚拟...
  • zzulp
  • zzulp
  • 2014年04月10日 15:54
  • 3276


Pascal数据集:cvpr2016-master-pascal,下面包含两个i2t和t2i,分别都要去调 输入数据:在两个各自文件夹中的data下 运行方法: 训练执行sh train_cub...
  • pku_langzi
  • pku_langzi
  • 2017年04月03日 19:36
  • 327

SQLServerException: Arithmetic overflow error converting numeric to data type numeric(1)

java.lang.RuntimeException: Arithmetic overflow err...
  • Neetgo
  • Neetgo
  • 2017年02月08日 14:40
  • 1086

SQLServer 中 错误 Error converting data type varchar to datetime 的解决方法

SQLServer 中 错误 “Error converting data type varchar to datetime” 可能是最常见的一个错误了, 通常这是由于输入日期字符串varchar 与...
  • batman9956
  • batman9956
  • 2014年01月01日 20:38
  • 5232

Error converting data type nvarchar to datetime

今天写了个存储过程,执行时把当前时间作为存储过程的参数,出现了不少问题。 最初的写法见error.sql,出错 Incorrect syntax near ')'. 是因为函数不能做为...
  • Tracy1990LG
  • Tracy1990LG
  • 2014年01月07日 17:19
  • 1569

【COCOS2DX-LUA 脚本开发之十三】解决lua项目编译Android出现get data from file failed、Cocos2dxActivity cannot be 路径等问题

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) CCString* pstrFileContent = CCString::createWith...
  • xiaominghimi
  • xiaominghimi
  • 2013年04月23日 17:56
  • 11818

SQLServerException: Arithmetic overflow error converting numeric to data type numeric(2)

上次提到,在客户环境发现这个问题 java.lang.RuntimeException: Ari...
  • Neetgo
  • Neetgo
  • 2017年02月28日 16:38
  • 1112

MongoDB Error

①,org.springframework.core.convert.ConverterNotFoundException: No converter found capable of     con...
  • luyee2010
  • luyee2010
  • 2013年08月09日 20:24
  • 4145
您举报文章:Library for Converting Data to and from C Structs for Lua 5.1