Lua Declare

lua-users home


LuaDeclare is a Lua module (see LuaBinaryModules), that provides a function binding mechanism for arbitrary win32 dynamic libraries.

VersionNotice: This page largely pertains to an earlier version of Lua (4.0 and 5.0beta) using a loadmodule extension. Lua 5.1 uses package.loadlib and require. Lua 5.0 uses loadlib.)

Usage Guide

The declare library is loaded with the following line:

assert(loadmodule "declare")

The declare module exports the following function:

declare(library, funcname, prototype, calltype)

The first parameter is the name of the library. The second parameter is the name of the string you want to bind. The third argument is a string that encodes the arguments and the return type of the function. The last parameter is optional. By default the call type is "cdecl", but you can also use "stdcall".

The format of the prototype is:


The encoding of the arguments is as follows:

A: a string in ANSI format.
c: Signed char value (8 bits)
C: Unsigned char value (8 bits)
s: Signed short value (16 bits)
S: Unsigned short value (16 bits)
i: Signed integer value (32 bits)
I: Unsigned integer value (32 bits)
l: Signed long value (64 bits)
L: Unsigned long value (64 bits)
f: Single-precision float in the native format (32 bits)
d: Double-precision float in the native format (64 bits)
v: void (only allowed for return values)

Here is an example of how to bind the win32 MessageBox? function:

MessageBox = declare("user32.dll", "MessageBox", "i=IAAI", "stdcall")

after doing this, you can use the function as follows:

MessageBox( 0, "this is", "a test", 0 )

You can also get additional information about the function in the following way:


To remove the function do:

MessageBox = nil

and the garbage collector will unload the library automatically.

See test-declare.lua to see an example.


The binding mechanism is currently quite slow, the real solution is to emit the binding code dynamically to avoid branches. In the meantime, you can reduce the cost by writting a few separate paths for cdecl and stdcall, and optimizing the argument checks.

lua_declare only supports function calls with simple data types. It's possible to support structures and additional data types, but you will have to extend the prototype declaration and parse it appropiately.


The author of LuaDeclare is IgnacioCastano

This code is based on the dynawrap code of Ton Plooy and Jeff Stong, that enabled the use of 'declare' statements in VBScript, and published it in WDJ.

Thanks also go to MartinSpernau for founding this gem and showing it to me.


LuaDeclare is actually available for Lua 4.0 only. A Lua 5.0 version will be available someday.

[Download] LuaDeclare for lua-4.0

Potential update for Lua 5.0 use [here]. It's not fully tested but passes the basic 'MessageBox?' test.

RecentChanges · preferences
edit · history
Last edited January 14, 2007 12:58 am GMT (diff)