Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / swig / Lua.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SWIG and Lua</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body bgcolor="#ffffff">
<H1><a name="Lua_nn1"></a>29 SWIG and Lua</H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Lua_nn2">Preliminaries</a>
<li><a href="#Lua_nn3">Running SWIG</a>
<ul>
<li><a href="#Lua_nn4">Compiling and Linking and Interpreter</a>
<li><a href="#Lua_nn5">Compiling a dynamic module</a>
<li><a href="#Lua_nn6">Using your module</a>
</ul>
<li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Lua_nn8">Modules</a>
<li><a href="#Lua_nn9">Functions</a>
<li><a href="#Lua_nn10">Global variables</a>
<li><a href="#Lua_nn11">Constants and enums</a>
<li><a href="#Lua_nn12">Pointers</a>
<li><a href="#Lua_nn13">Structures</a>
<li><a href="#Lua_nn14">C++ classes</a>
<li><a href="#Lua_nn15">C++ inheritance</a>
<li><a href="#Lua_nn16">Pointers, references, values, and arrays</a>
<li><a href="#Lua_nn17">C++ overloaded functions</a>
<li><a href="#Lua_nn18">C++ operators</a>
<li><a href="#Lua_nn19">Class extension with %extend</a>
<li><a href="#Lua_nn20">C++ templates</a>
<li><a href="#Lua_nn21">C++ Smart Pointers</a>
</ul>
<li><a href="#Lua_nn22">Details on the Lua binding</a>
<ul>
<li><a href="#Lua_nn23">Binding global data into the module.</a>
<li><a href="#Lua_nn24">Userdata and Metatables</a>
<li><a href="#Lua_nn25">Memory management</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). Its also a <em>really</em> tiny language, less than 6000 lines of code, which compiles to &lt;100 kilobytes of binary code. It can be found at <a href="http://www.lua.org">http://www.lua.org</a>
</p>
<H2><a name="Lua_nn2"></a>29.1 Preliminaries</H2>
<p>
The current SWIG implementation is designed to work with Lua 5.0. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms).
</p>
<p>
Note: Lua 5.1 (alpha) has just (as of September 05) been released. The current version of SWIG will produce wrappers which are compatible with Lua 5.1, though the dynamic loading mechanism has changed (see below). The configure script and makefiles should work correctly with with Lua 5.1, though some small tweaks may be needed.
</p>
<H2><a name="Lua_nn3"></a>29.2 Running SWIG</H2>
<p>
Suppose that you defined a SWIG module such as the following:
</p>
<div class="code"><pre>
%module example
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo;
</pre></div>
<p>
To build a Lua module, run SWIG using the <tt>-lua</tt> option.
</p>
<div class="shell"><pre>
$ swig -lua example.i
</pre></div>
<p>
If building a C++ extension, add the <tt>-c++</tt> option:
</p>
<div class="shell"><pre>
$ swig -c++ -lua example.i
</pre></div>
<p>
This creates a C/C++ source file <tt>example_wrap.c</tt> or <tt>example_wrap.cxx</tt>. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.
</p>
<p>
The name of the wrapper file is derived from the name of the input file. For example, if the input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>. To change this, you can use the -o option. The wrappered module will export one function <tt>"int Example_Init(LuaState* L)"</tt> which must be called to register the module with the Lua interpreter. The name "Example_Init" depends upon the name of the module. Note: SWIG will automatically capitalise the module name, so <tt>"module example;"</tt> becomes <tt>"Example_Init"</tt>.
</p>
<H3><a name="Lua_nn4"></a>29.2.1 Compiling and Linking and Interpreter</H3>
<p>
Normally Lua is embedded into another program and will be statically linked. An extremely simple stand-alone interpreter (<tt>min.c</tt>) is given below:
</p>
<div class="code"><pre>
#include &lt;stdio.h&gt;
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
extern int Example_Init(LuaState* L); // declare the wrapped module
int main(int argc,char* argv[])
{
lua_State *L;
if (argc<2)
{
printf("%s: &lt;filename.lua&gt;\n",argv[0]);
return 0;
}
L=lua_open();
luaopen_base(L); // load basic libs (eg. print)
Example_Init(L); // load the wrappered module
if (luaL_loadfile(L,argv[1])==0) // load and run the file
lua_pcall(L,0,0,0);
else
printf("unable to load %s\n",argv[1]);
lua_close(L);
return 0;
}
</pre></div>
<p>
A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",Example_Init}</tt>, at the relevant place.
</p>
<p>
The exact commands for doing this vary from platform to platform. Here is a possible set of commands of doing this:
</p>
<div class="shell"><pre>
$ swig -lua example.i
$ gcc -I/usr/include/lua -c min.c -o min.o
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
</pre></div>
<H3><a name="Lua_nn5"></a>29.2.2 Compiling a dynamic module</H3>
<p>
Most, but not all platforms support the dynamic loading of modules (Windows &amp; Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can be used. The commands will be something like this:
</p>
<div class="shell"><pre>
$ swig -lua example.i
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
</pre></div>
<p>
You will also need an interpreter with the loadlib function (such as the default interpreter compiled with Lua). In order to dynamically load a module you must call the loadlib function with two parameters: the filename of the shared library, and the function exported by SWIG. Calling loadlib should return the function, which you then call to initialise the module
</p>
<div class="targetlang"><pre>
my_init=loadlib("example.so","Example_Init") -- for Unix/Linux
--my_init=loadlib("example.dll","Example_Init") -- for Windows
assert(my_init) -- name sure its not nil
my_init() -- call the init fn of the lib
</pre></div>
<p>
Or can be done in a single line of Lua code
</p>
<div class="targetlang"><pre>
assert(loadlib("example.so","Example_Init"))()
</pre></div>
<p>
Update for Lua 5.1 (alpha):<br>
The wrappers produced by SWIG can be compiled and linked with Lua 5.1. The loading is now much simpler.
</p>
<div class="targetlang"><pre>
require("example")
</pre></div>
<H3><a name="Lua_nn6"></a>29.2.3 Using your module</H3>
<p>
Assuming all goes well, you will be able to this:
</p>
<div class="targetlang"><pre>
$ ./my_lua
&gt; print(example.gcd(4,6))
2
&gt; print(example.Foo)
3
&gt; example.Foo=4
&gt; print(example.Foo)
4
&gt;
</pre></div>
<H2><a name="Lua_nn7"></a>29.3 A tour of basic C/C++ wrapping</H2>
<p>
By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.
</p>
<H3><a name="Lua_nn8"></a>29.3.1 Modules</H3>
<p>
The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.
</p>
<H3><a name="Lua_nn9"></a>29.3.2 Functions</H3>
<p>
Global functions are wrapped as new Lua built-in functions. For example,
</p>
<div class="code"><pre>
%module example
int fact(int n);</pre></div>
<p>
creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
</p>
<div class="targetlang"><pre>
&gt; print example.fact(4)
24
&gt;
</pre></div>
<p>
To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care.
</p>
<div class="targetlang"><pre>
&gt; for k,v in pairs(example) do _G[k]=v end
&gt; print(fact(4))
24
&gt;
</pre></div>
<p>
It is also possible to rename the module with an assignment.
</p>
<div class="targetlang"><pre>
&gt; e=example
&gt; print(e.fact(4))
24
&gt; print(example.fact(4))
24
</pre></div>
<H3><a name="Lua_nn10"></a>29.3.3 Global variables</H3>
<p>
Global variables (which are linked to C code) are supported, and appear to be just another variable in Lua. However the actual mechanism is more complex. Given a global variable:
</p>
<div class="code"><pre>%module example
extern double Foo;
</pre></div>
<p>
SWIG will actually generate two functions <tt>example.Foo_set()</tt> and <tt>example.Foo_get()</tt>. It then adds a metatable to the table 'example' to call these functions at the correct time (when you attempt to set or get examples.Foo). Therefore if you were to attempt to assign the global to another variable, you will get a local copy within the interpreter, which is no longer linked to the C code.
</p>
<div class="targetlang"><pre>
&gt; print(example.Foo)
3
&gt; c=example.Foo -- c is a COPY of example.Foo, not the same thing
&gt; example.Foo=4
&gt; print(c)
3
&gt; c=5 -- this will not effect the original example.Foo
&gt; print(example.Foo,c)
4 5
</pre></div>
<p>
Its is therefore not possible to 'move' the global variable into the global namespace as it is with functions. It is however, possible to rename the module with an assignment, to make it more convenient.
</p>
<div class="targetlang"><pre>
&gt; e=example
&gt; -- e and example are the same table
&gt; -- so e.Foo and example.Foo are the same thing
&gt; example.Foo=4
&gt; print(e.Foo)
4
</pre></div>
<p>
If a variable is marked with the immutable directive then any attempts to set this variable are silently ignored.
</p>
<p>
Another interesting feature is that it is not possible to add new values into the module from within the interpreter, this is because of the metatable to deal with global variables. It is possible (though not recommended) to use rawset() to add a new value.
</p>
<div class="targetlang"><pre>
&gt; -- example.PI does not exist
&gt; print(example.PI)
nil
&gt; example.PI=3.142 -- assign failed, example.PI does still not exist
&gt; print(example.PI)
nil
&gt; -- a rawset will work, after this the value is added
&gt; rawset(example,"PI",3.142)
&gt; print(example.PI)
3.142
</pre></div>
<H3><a name="Lua_nn11"></a>29.3.4 Constants and enums</H3>
<p>
Because Lua doesn't really have the concept of constants, C/C++ constants are not really constant in Lua. They are actually just a copy of the value into the Lua interpreter. Therefore they can be changed just as any other value. For example given some constants:
</p>
<div class="code"><pre>%module example
%constant int ICONST=42;
#define SCONST "Hello World"
enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
</pre></div>
<p>
This is 'effectively' converted into the following Lua code:
</p>
<div class="targetlang"><pre>
example.ICONST=42
example.SCONST="Hello World"
example.SUNDAY=0
....
</pre></div>
<p>
Constants are not guaranteed to remain constant in Lua. The name of the constant could be accidentally reassigned to refer to some other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.
</p>
<H3><a name="Lua_nn12"></a>29.3.5 Pointers</H3>
<p>
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the &lt;file.h&gt; interface:
</p>
<div class="code"><pre>%module example
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre></div>
<p>
When wrapped, you will be able to use the functions in a natural way from Lua. For example:
</p>
<div class="targetlang"><pre>
&gt; f=example.fopen("junk","w")
&gt; example.fputs("Hello World",f)
&gt; example.fclose(f)
</pre></div>
<p>
Unlike many scripting languages, Lua has had support for pointers to C/C++ object built in for a long time. They are called 'userdata'. Unlike many other SWIG versions which use some kind of encoded character string, all objects will be represented as a userdata. The SWIG-Lua bindings provides a special function <tt>swig_type()</tt>, which if given a userdata object will return the type of object pointed to as a string (assuming it was a SWIG wrappered object).
</p>
<div class="targetlang"><pre>
&gt; print(f)
userdata: 003FDA80
&gt; print(swig_type(f))
_p_FILE -- its a FILE*
</pre></div>
<p>
Lua enforces the integrity of its userdata, so it is virtually impossible to corrupt the data. But as the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes &amp; structs (see below). One final note: if a function returns a NULL pointer, this is not encoded as a userdata, but as a Lua nil.
</p>
<div class="targetlang"><pre>
&gt; f=example.fopen("not there","r") -- this will return a NULL in C
&gt; print(f)
nil
</pre></div>
<H3><a name="Lua_nn13"></a>29.3.6 Structures</H3>
<p>
If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example,
</p>
<div class="code"><pre>struct Point{
int x,y;
};
</pre></div>
<p>
is used as follows:
</p>
<div class="targetlang"><pre>
&gt; p=example.Point()
&gt; p.x=3
&gt; p.y=5
&gt; print(p.x,p.y)
3 5
&gt;
</pre></div>
<p>
Similar access is provided for unions and the data members of C++ classes.<br>
SWIG will also create a function <tt>new_Point()</tt> which also creates a new Point structure.
</p>
<p>
If you print out the value of p in the above example, you will see something like this:
</p>
<div class="targetlang"><pre>
&gt; print(p)
userdata: 003FA320
</pre></div>
<p>
Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG creates some accessor/mutator functions <tt>Point_set_x()</tt> and <tt>Point_get_x()</tt>. These will be wrappered, and then added to the metatable added to the userdata. This provides the natural access to the member variables that were shown above (see end of the document for full details).
</p>
<p>
<tt>const</tt> members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutable's, setting attempts will be silently ignored. For example:
</p>
<div class="code"><pre>struct Foo {
...
%immutable;
int x; // Read-only members
char *name;
%mutable;
...
};
</pre></div>
<p>
The mechanism for managing char* members as well as array members is similar to other languages. It is somewhat cumbersome and should probably be better handled by defining of typemaps (described later).
</p>
<p>
When a member of a structure is itself a structure, it is handled as a pointer. For example, suppose you have two structures like this:
</p>
<div class="code"><pre>struct Foo {
int a;
};
struct Bar {
Foo f;
};
</pre></div>
<p>
Now, suppose that you access the f attribute of Bar like this:
</p>
<div class="targetlang"><pre>
&gt; b = Bar()
&gt; x = b.f
</pre></div>
<p>
In this case, x is a pointer that points to the Foo that is inside b. This is the same value as generated by this C code:
</p>
<div class="code"><pre>
Bar b;
Foo *x = &amp;b-&gt;f; // Points inside b
</pre></div>
<p>
Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
</p>
<div class="targetlang"><pre>
&gt; b = Bar()
&gt; b.f.a = 3 -- Modify attribute of structure member
&gt; x = b.f
&gt; x.a = 3 -- Modifies the same structure
</pre></div>
<H3><a name="Lua_nn14"></a>29.3.7 C++ classes</H3>
<p>
C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
</p>
<div class="code"><pre>class List {
public:
List();
~List();
int search(char *item);
void insert(char *item);
void remove(char *item);
char *get(int n);
int length;
};
</pre></div>
<p>
you can use it in Lua like this:
</p>
<div class="targetlang"><pre>
&gt; l = example.List()
&gt; l.insert("Ale")
&gt; l.insert("Stout")
&gt; l.insert("Lager")
&gt; print(l.get(1))
Stout
&gt; print(l.length)
3
&gt;
</pre></div>
<p>
Class data members are accessed in the same manner as C structures. Static class members present a special problem for Lua, as Lua doesn't have support for such features. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this:
</p>
<div class="targetlang"><pre>class Spam {
public:
static void foo();
static int bar;
};
</pre></div>
<p>
In Lua, the static members can be accessed as follows:
</p>
<div class="code"><pre>
&gt; example.Spam_foo() -- Spam::foo() the only way currently
&gt; a=example.Spam_bar_get() -- Spam::bar the hard way
&gt; a=example.Spam_bar -- Spam::bar the nicer way
&gt; example.Spam_bar_set(b) -- Spam::bar the hard way
&gt; example.Spam_bar=b -- Spam::bar the nicer way
</pre></div>
<p>
It is not (currently) possible to access static members of an instance:
</p>
<div class="targetlang"><pre>
&gt; s=example.Spam() -- s is a Spam instance
&gt; s.foo() -- Spam::foo() via an instance
-- does NOT work
</pre></div>
<H3><a name="Lua_nn15"></a>29.3.8 C++ inheritance</H3>
<p>
SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
</p>
<div class="code"><pre>class Foo {
...
};
class Bar : public Foo {
...
};
</pre></div>
<p>
And if you have functions like this
</p>
<div class="code"><pre>void spam(Foo *f);
</pre></div>
<p>
then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
</p>
<p>
It is safe to use multiple inheritance with SWIG.
</p>
<H3><a name="Lua_nn16"></a>29.3.9 Pointers, references, values, and arrays</H3>
<p>
In C++, there are many different ways a function might receive and manipulate objects. For example:
</p>
<div class="code"><pre>void spam1(Foo *x); // Pass by pointer
void spam2(Foo &amp;x); // Pass by reference
void spam3(Foo x); // Pass by value
void spam4(Foo x[]); // Array of objects
</pre></div>
<p>
In SWIG, there is no detailed distinction like this--specifically, there are only "objects". There are no pointers, references, arrays, and so forth. Because of this, SWIG unifies all of these types together in the wrapper code. For instance, if you actually had the above functions, it is perfectly legal to do this:
</p>
<div class="targetlang"><pre>
&gt; f = Foo() -- Create a Foo
&gt; spam1(f) -- Ok. Pointer
&gt; spam2(f) -- Ok. Reference
&gt; spam3(f) -- Ok. Value.
&gt; spam4(f) -- Ok. Array (1 element)
</pre></div>
<p>
Similar behaviour occurs for return values. For example, if you had functions like this,
</p>
<div class="code"><pre>Foo *spam5();
Foo &amp;spam6();
Foo spam7();
</pre></div>
<p>
then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Lua will release this memory when the return value is garbage collected). The other two are pointers which are assumed to be managed by the C code and so will not be garbage collected.
</p>
<H3><a name="Lua_nn17"></a>29.3.10 C++ overloaded functions</H3>
<p>
C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
</p>
<div class="code"><pre>void foo(int);
void foo(char *c);
</pre></div>
<p>
You can use them in Lua in a straightforward manner:
</p>
<div class="targetlang"><pre>
&gt; foo(3) -- foo(int)
&gt; foo("Hello") -- foo(char *c)
</pre></div>
<p>
However due to Lua's coercion mechanism is can sometimes do strange things.
</p>
<div class="targetlang"><pre>
&gt; foo("3") -- "3" can be coerced into an int, so it calls foo(int)!
</pre></div>
<p>
As this coercion mechanism is an integral part of Lua, there is no easy way to get around this other than renaming of functions (see below).
</p>
<p>
Similarly, if you have a class like this,
</p>
<div class="code"><pre>class Foo {
public:
Foo();
Foo(const Foo &amp;);
...
};
</pre></div>
<p>
you can write Lua code like this:
</p>
<div class="targetlang"><pre>
&gt; f = Foo() -- Create a Foo
&gt; g = Foo(f) -- Copy f
</pre></div>
<p>
Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
</p>
<div class="code"><pre>void spam(int);
void spam(short);
</pre></div>
<p>
or
</p>
<DIV CLASS="CODE"><PRE>VOID FOO(bAR *B);
void foo(Bar &amp;b);
</pre></div>
<p>
If declarations such as these appear, you will get a warning message like this:
</p>
<div class="shell"><pre>
example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
at example.i:11.
</pre></div>
<p>
To fix this, you either need to ignore or rename one of the methods. For example:
</p>
<div class="code"><pre>%rename(spam_short) spam(short);
...
void spam(int);
void spam(short); // Accessed as spam_short
</pre></div>
<p>
or
</p>
<div class="code"><pre>%ignore spam(short);
...
void spam(int);
void spam(short); // Ignored
</pre></div>
<p>
SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.
</p>
<p>
Please refer to the "SWIG and C++" chapter for more information about overloading.
</p>
<p>
Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.
</p>
<H3><a name="Lua_nn18"></a>29.3.11 C++ operators</H3>
<p>
Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
</p>
<div class="code"><pre>class Complex {
private:
double rpart, ipart;
public:
Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &amp;operator=(const Complex &amp;c);
Complex operator+(const Complex &amp;c) const;
Complex operator-(const Complex &amp;c) const;
Complex operator*(const Complex &amp;c) const;
Complex operator-() const;
double re() const { return rpart; }
double im() const { return ipart; }
};
</pre></div>
<p>
When wrapped, it works like you expect:
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3,4)
&gt; d = Complex(7,8)
&gt; e = c + d
&gt; e:re()
10.0
&gt; e:im()
12.0
</pre></div>
<p>
(Note: for calling methods of a class, you use <tt>class:method(args)</tt>, not <tt>class.method(args)</tt>, its an easy mistake to make.)
</p>
<p>
One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this
</p>
<div class="targetlang"><pre>class Complex {
...
friend Complex operator+(double, const Complex &amp;c);
...
};
</pre></div>
<p>
then SWIG doesn't know what to do with the friend function--in fact, it simply ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:
</p>
<div class="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &amp;);
...
Complex operator+(double, const Complex &amp;c);
</pre></div>
<p>
There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
</p>
<p>
Also, be aware that certain operators don't map cleanly to Lua, and some Lua operators don't map cleanly to C++ operators. For instance, overloaded assignment operators don't map to Lua semantics and will be ignored, and C++ doesn't support Lua's concatenation operator (<tt>..</tt>).
</p>
<p>
In order to keep maximum compatibility within the different languages in SWIG, the Lua bindings uses the same set of operator names as python. Although internally it renames the functions to something else (on order to work with Lua).
<p>
The current list of operators which can be overloaded (and the alternative function names) are:<ul>
<li><tt>__add__</tt> operator+
<li><tt>__sub__</tt> operator-
<li><tt>__mul__</tt> operator *
<li><tt>__div__</tt> operator/
<li><tt>__neg__</tt> unary minus
<li><tt>__call__</tt> operator<tt>()</tt> (often used in functor classes)
<li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>^</tt>)
<li><tt>__concat__</tt> the concatenation operator (SWIG maps C++'s <tt>~</tt> to Lua's <tt>..</tt>)
<li><tt>__eq__</tt> operator<tt>==</tt>
<li><tt>__lt__</tt> operator<tt>&lt;</tt>
<li><tt>__le__</tt> operator<tt>&lt;=</tt>
</ul>
<p>
Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=,&gt;,&gt;=) are achieved by using a logical not applied to the results of other operators.
</p>
<p>
The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
<li>++ and --<li>+=,-=,*= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
<p>
SWIG also accepts the <tt>__str__()</tt> member function which converts an object to a string. This function should return a const char*, preferably to static memory. This will be used for the <tt>print()</tt> and <tt>tostring()</tt> functions in Lua. Assuming the complex class has a function
</p>
<div class="code"><pre>const char* __str__()
{
static char buffer[255];
sprintf(buffer,"Complex(%g,%g)",this-&gt;re(),this-&gt;im());
return buffer;
}
</pre></div>
<p>
Then this will support the following code in Lua
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3,4)
&gt; d = Complex(7,8)
&gt; e = c + d
&gt; print(e)
Complex(10,12)
&gt; s=tostring(e) -- s is the number in string form
&gt; print(s)
Complex(10,12)
</pre></div>
<p>
It is also possible to overload the operator<tt>[]</tt>, but currently this cannot be automatically performed. To overload the operator<tt>[]</tt> you need to provide two functions, <tt>__getitem__()</tt> and <tt>__setitem__()</tt>
</p>
<div class="code"><pre>class Complex
{
//....
double __getitem__(int i)const; // i is the index, returns the data
void __setitem__(int i,double d); // i is the index, d is the data
};
</pre></div>
<H3><a name="Lua_nn19"></a>29.3.12 Class extension with %extend</H3>
<p>
One of the more interesting features of SWIG is that it can extend structures and classes with new methods. In the previous section, the Complex class would have benefited greatly from an __str__() method as well as some repairs to the operator overloading. It can also be used to add additional functions to the class if they are needed.
</p>
<p>
Take the original Complex class
</p>
<div class="code"><pre>class Complex {
private:
double rpart, ipart;
public:
Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &amp;operator=(const Complex &amp;c);
Complex operator+(const Complex &amp;c) const;
Complex operator-(const Complex &amp;c) const;
Complex operator*(const Complex &amp;c) const;
Complex operator-() const;
double re() const { return rpart; }
double im() const { return ipart; }
};
</pre></div>
<p>
Now we extend it with some new code
</p>
<div class="code"><pre>%extend Complex {
const char *__str__() {
static char tmp[1024];
sprintf(tmp,"Complex(%g,%g)", self-&gt;re(),self-&gt;im());
return tmp;
}
bool operator==(const Complex&amp; c)
{ return (self-&gt;re()==c.re() &amp;&amp; self-&gt;im()==c.im();}
};
</pre></div>
<p>
Now, in Lua
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3,4)
&gt; d = Complex(7,8)
&gt; e = c + d
&gt; print(e) -- print uses __str__ to get the string form to print
Complex(10,12)
&gt; print(e==Complex(10,12)) -- testing the == operator
true
&gt; print(e!=Complex(12,12)) -- the != uses the == operator
true
</pre></div>
<p>
Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the 'self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).
</p>
<H3><a name="Lua_nn20"></a>29.3.13 C++ templates</H3>
<p>
C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the template directive. For example:
</p>
<div class="code"><pre>%module example
%{
#include "pair.h"
%}
template&lt;class T1, class T2&gt;
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair();
pair(const T1&amp;, const T2&amp;);
~pair();
};
%template(pairii) pair&lt;int,int&gt;;
</pre></div>
<p>
In Lua:
</p>
<div class="targetlang"><pre>
&gt; p = example.pairii(3,4)
&gt; print(p.first,p.second)
3 4
</pre></div>
<p>
Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.
</p>
<H3><a name="Lua_nn21"></a>29.3.14 C++ Smart Pointers</H3>
<p>
In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator-&gt;() like this:
</p>
<div class="code"><pre>template&lt;class T&gt; class SmartPtr {
...
T *operator-&gt;();
...
}
</pre></div>
<p>
Then, if you have a class like this,
</p>
<div class="code"><pre>class Foo {
public:
int x;
int bar();
};
</pre></div>
<p>
A smart pointer would be used in C++ as follows:
</p>
<div class="code"><pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
...
p-&gt;x = 3; // Foo::x
int y = p-&gt;bar(); // Foo::bar
</pre></div>
<p>
To wrap this, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using template if necessary. For example:
</p>
<div class="code"><pre>%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre></div>
<p>
Now, in Lua, everything should just "work":
</p>
<div class="targetlang"><pre>
&gt; p = example.CreateFoo() -- Create a smart-pointer somehow
&gt; p.x = 3 -- Foo::x
&gt; print(p:bar()) -- Foo::bar
</pre></div>
<p>
If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method. For example:
</p>
<div class="targetlang"><pre>
&gt; f = p:__deref__() -- Returns underlying Foo *
</pre></div>
<H2><a name="Lua_nn22"></a>29.4 Details on the Lua binding</H2>
<p>
In the previous section, a high-level view of Lua wrapping was presented. Obviously a lot of stuff happens behind the scenes to make this happen. This section will explain some of the low-level details on how this is achieved.
</p>
<p>
<i>If you just want to use SWIG and don't care how it works, then stop reading here. This is going into the guts of the code and how it works. Its mainly for people who need to know whats going on within the code.
</i>
</p>
<H3><a name="Lua_nn23"></a>29.4.1 Binding global data into the module.</H3>
<p>
Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
</p>
<div class="code"><pre>%module example;
extern double Foo;
</pre></div>
<p>
SWIG will effectively generate the pair of functions
</p>
<div class="code"><pre>void Foo_set(double);
double Foo_get();
</pre></div>
<p>
At initialisation time, it will then add to the interpreter a table called 'example', which represents the module. It will then add all its functions to the module. But it also adds a metatable to this table, which has two functions (<tt>__index</tt> and <tt>__newindex</tt>) as well as two tables (<tt>.get</tt> and <tt>.set</tt>) The following Lua code will show these hidden features.
</p>
<div class="targetlang"><pre>
&gt; print(example)
table: 003F8F90
&gt; m=getmetatable(example)
&gt; table.foreach(m,print)
.set table: 003F9088
.get table: 003F9038
__index function: 003F8FE0
__newindex function: 003F8FF8
&gt; g=m['.get']
&gt; table.foreach(g,print)
Foo function: 003FAFD8
&gt;
</pre></div>
<p>
The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)
</p>
<p>
The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
</p>
<div class="targetlang"><pre>
function __index(mod,name)
local g=getmetatable(mod)['.get'] -- gets the table
if not g then return nil end
local f=g[name] -- looks for the function
-- calls it &amp; returns the value
if type(f)=="function" then return f() end
return nil
end
function __newindex(mod,name,value)
local s=getmetatable(mod)['.set'] -- gets the table
if not s then return end
local f=s[name] -- looks for the function
-- calls it to set the value
if type(f)=="function" then f(value) end
end
</pre></div>
<p>
That way when you call '<tt>a=example.Foo</tt>', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code '<tt>example.Foo=10</tt>', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.
</p>
<H3><a name="Lua_nn24"></a>29.4.2 Userdata and Metatables</H3>
<p>
As mentioned earlier, classes and structures, are all held as pointer, using the Lua 'userdata' structure. This structure is actually a pointer to a C structure 'swig_lua_userdata', which contains the pointer to the data, a pointer to the swig_type_info (an internal SWIG struct) and a flag which marks if the object is to be disposed of when the interpreter no longer needs it. The actual accessing of the object is done via the metatable attached to this userdata.
</p>
<p>
The metatable is a Lua 5.0 feature (which is also why SWIG cannot wrap Lua 4.0). Its a table which holds a list of functions, operators and attributes. This is what gives the userdata the feeling that it is a real object and not just a hunk of memory.
</p>
<p>
Given a class
</p>
<div class="code"><pre>%module excpp;
class Point
{
public:
int x,y;
Point(){x=y=0;}
~Point(){}
virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
};
</pre></div>
<p>
SWIG will create a module excpp, with all the various function inside. However to allow the intuitive use of the userdata is also creates up a set of metatables. As seen in the above section on global variables, use of the metatables allows for wrappers to be used intuitively. To save effort, the code creates one metatable per class and stores it inside Lua's registry. Then when an new object is instantiated, the metatable is found in the registry and the userdata associated to the metatable. Currently derived classes make a complete copy of the base classes table and then add on their own additional function.
</p>
<p>
Some of the internals can be seen by looking at a classes metatable.
</p>
<div class="targetlang"><pre>
&gt; p=excpp.Point()
&gt; print(p)
userdata: 003FDB28
&gt; m=getmetatable(p)
&gt; table.foreach(m,print)
.type Point
__gc function: 003FB6C8
__newindex function: 003FB6B0
__index function: 003FB698
.get table: 003FB4D8
.set table: 003FB500
.fn table: 003FB528
</pre></div>
<p>
The '.type' attribute is the string which is returned from a call to swig_type(). The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the classes destructor function)
</p>
<p>
The Lua equivalent of the code for enabling functions looks a little like this
</p>
<div class="targetlang"><pre>
function __index(obj,name)
local m=getmetatable(obj) -- gets the metatable
if not m then return nil end
local g=m['.get'] -- gets the attribute table
if not g then return nil end
local f=g[name] -- looks for the get_attribute function
-- calls it &amp; returns the value
if type(f)=="function" then return f() end
-- ok, so it not an attribute, maybe its a function
local fn=m['.fn'] -- gets the function table
if not fn then return nil end
local f=fn[name] -- looks for the function
-- if found the fn then return the function
-- so the interpreter can call it
if type(f)=="function" then return f end
return nil
end
</pre></div>
<p>
So when 'p:Print()' is called, the __index looks on the object metatable for a 'Print' attribute, then looks for a 'Print' function. When it finds the function, it returns the function, and then interpreter can call 'Point_Print(p)'
</p>
<p>
In theory, you can play with this usertable &amp; add new features, but remember that it is a shared table between all instances of one class, and you could very easily corrupt the functions in all the instances.
</p>
<p>
Note: Both the opaque structures (like the FILE*) and normal wrappered classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures has do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them.
</p>
<p>
Note: Operator overloads are basically done in the same way, by adding functions such as '__add' &amp; '__call' to the classes metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
</p>
<H3><a name="Lua_nn25"></a>29.4.3 Memory management</H3>
<p>
Lua is very helpful with the memory management. The 'swig_lua_userdata' is fully managed by the interpreter itself. This means that neither the C code nor the Lua code can damage it. Once a piece of userdata has no references to it, it is not instantly collected, but will be collected when Lua deems is necessary. (You can force collection by calling the Lua function <tt>collectgarbage()</tt>). Once the userdata is about to be free'ed, the interpreter will check the userdata for a metatable and for a function '__gc'. If this exists this is called. For all complete types (ie normal wrappered classes &amp; structs) this should exist. The '__gc' function will check the 'swig_lua_userdata' to check for the 'own' field and if this is true (which is will be for all owned data's) it will then call the destructor on the pointer.
</p>
<p>
It is currently not recommended to edit this field or add some user code, to change the behaviour. Though for those who wish to try, here is where to look.
</p>
<p>
It is also currently not possible to change the ownership flag on the data (unlike most other scripting languages, Lua does not permit access to the data from within the interpreter)
</p>
</body>
</html>