1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG and Lua</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="Lua_nn1"></a>23 SWIG and Lua</H1>
11 <div class="sectiontoc">
13 <li><a href="#Lua_nn2">Preliminaries</a>
14 <li><a href="#Lua_nn3">Running SWIG</a>
16 <li><a href="#Lua_nn4">Compiling and Linking and Interpreter</a>
17 <li><a href="#Lua_nn5">Compiling a dynamic module</a>
18 <li><a href="#Lua_nn6">Using your module</a>
20 <li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
22 <li><a href="#Lua_nn8">Modules</a>
23 <li><a href="#Lua_nn9">Functions</a>
24 <li><a href="#Lua_nn10">Global variables</a>
25 <li><a href="#Lua_nn11">Constants and enums</a>
26 <li><a href="#Lua_nn12">Pointers</a>
27 <li><a href="#Lua_nn13">Structures</a>
28 <li><a href="#Lua_nn14">C++ classes</a>
29 <li><a href="#Lua_nn15">C++ inheritance</a>
30 <li><a href="#Lua_nn16">Pointers, references, values, and arrays</a>
31 <li><a href="#Lua_nn17">C++ overloaded functions</a>
32 <li><a href="#Lua_nn18">C++ operators</a>
33 <li><a href="#Lua_nn19">Class extension with %extend</a>
34 <li><a href="#Lua_nn20">C++ templates</a>
35 <li><a href="#Lua_nn21">C++ Smart Pointers</a>
36 <li><a href="#Lua_nn22">C++ Exceptions</a>
38 <li><a href="#Lua_nn23">Typemaps</a>
40 <li><a href="#Lua_nn24">What is a typemap?</a>
41 <li><a href="#Lua_nn25">Using typemaps</a>
42 <li><a href="#Lua_nn26">Typemaps and arrays</a>
43 <li><a href="#Lua_nn27">Typemaps and pointer-pointer functions</a>
45 <li><a href="#Lua_nn28">Writing typemaps</a>
47 <li><a href="#Lua_nn29">Typemaps you can write</a>
48 <li><a href="#Lua_nn30">SWIG's Lua-C API</a>
50 <li><a href="#Lua_nn31">Customization of your Bindings</a>
52 <li><a href="#Lua_nn32">Writing your own custom wrappers</a>
53 <li><a href="#Lua_nn33">Adding additional Lua code</a>
55 <li><a href="#Lua_nn34">Details on the Lua binding</a>
57 <li><a href="#Lua_nn35">Binding global data into the module.</a>
58 <li><a href="#Lua_nn36">Userdata and Metatables</a>
59 <li><a href="#Lua_nn37">Memory management</a>
68 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 <100 kilobytes of binary code. It can be found at <a href="http://www.lua.org">http://www.lua.org</a>
70 <H2><a name="Lua_nn2"></a>23.1 Preliminaries</H2>
74 The current SWIG implementation is designed to work with Lua 5.0.x and Lua 5.1.x. 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).
76 <H2><a name="Lua_nn3"></a>23.2 Running SWIG</H2>
80 Suppose that you defined a SWIG module such as the following:
82 <div class="code"><pre>
87 int gcd(int x, int y);
91 To build a Lua module, run SWIG using the <tt>-lua</tt> option.
93 <div class="shell"><pre>
97 If building a C++ extension, add the <tt>-c++</tt> option:
99 <div class="shell"><pre>
100 $ swig -c++ -lua example.i
103 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.
106 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 luaopen_example(lua_State* L)"</tt> which must be called to register the module with the Lua interpreter. The name "luaopen_example" depends upon the name of the module.
108 <H3><a name="Lua_nn4"></a>23.2.1 Compiling and Linking and Interpreter</H3>
112 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:
114 <div class="code"><pre>
115 #include <stdio.h>
120 extern int luaopen_example(lua_State* L); // declare the wrapped module
122 int main(int argc,char* argv[])
127 printf("%s: <filename.lua>\n",argv[0]);
131 luaopen_base(L); // load basic libs (eg. print)
132 luaopen_example(L); // load the wrappered module
133 if (luaL_loadfile(L,argv[1])==0) // load and run the file
136 printf("unable to load %s\n",argv[1]);
142 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 & add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place.
145 The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
147 <div class="shell"><pre>
148 $ swig -lua example.i -o example_wrap.c
149 $ gcc -I/usr/include/lua -c min.c -o min.o
150 $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
151 $ gcc -c example.c -o example.o
152 $ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
155 <H3><a name="Lua_nn5"></a>23.2.2 Compiling a dynamic module</H3>
159 Most, but not all platforms support the dynamic loading of modules (Windows & 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:
161 <div class="shell"><pre>
162 $ swig -lua example.i -o example_wrap.c
163 $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
164 $ gcc -c example.c -o example.o
165 $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
168 The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x. The loading is extremely simple.
170 <div class="targetlang"><pre>
174 For those using Lua 5.0.x, 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
176 <div class="targetlang"><pre>
177 my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux
178 --my_init=loadlib("example.dll","luaopen_example") -- for Windows
179 assert(my_init) -- name sure its not nil
180 my_init() -- call the init fn of the lib
183 Or can be done in a single line of Lua code
185 <div class="targetlang"><pre>
186 assert(loadlib("example.so","luaopen_example"))()
191 If the code didn't work, don't panic. The best thing to do is to copy the module and your interpreter into a single directory and then execute the interpreter and try to manually load the module (take care, all this code is case sensitive).
193 <div class="targetlang"><pre>
194 a,b,c=package.loadlib("example.so","luaopen_example") -- for Unix/Linux
195 --a,b,c=package.loadlib("example.dll","luaopen_example") -- for Windows
199 Note: for Lua 5.0:<br>
200 The loadlib() function is in the global namespace, not in package. So its just loadlib().
203 if 'a' is a function, this its all working fine, all you need to do is call it
205 <div class="targetlang"><pre>
209 to load your library which will add a table 'example' with all the functions added.
212 If it doesn't work, look at the error messages, in particular mesage 'b'<br>
213 <tt> The specified module could not be found.</tt><br>
214 Means that is cannot find the module, check your the location and spelling of the module.<br>
215 <tt> The specified procedure could not be found.</tt><br>
216 Means that it loaded the module, but cannot find the named function. Again check the spelling, and if possible check to make sure the functions were exported correctly.<br>
217 <tt> 'loadlib' not installed/supported</tt><br>
218 Is quite obvious (Go back and consult the Lua documents on how to enable loadlib for your platform).
223 <H3><a name="Lua_nn6"></a>23.2.3 Using your module</H3>
227 Assuming all goes well, you will be able to this:
229 <div class="targetlang"><pre>
231 > print(example.gcd(4,6))
233 > print(example.Foo)
236 > print(example.Foo)
241 <H2><a name="Lua_nn7"></a>23.3 A tour of basic C/C++ wrapping</H2>
245 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.
247 <H3><a name="Lua_nn8"></a>23.3.1 Modules</H3>
251 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.
253 <H3><a name="Lua_nn9"></a>23.3.2 Functions</H3>
257 Global functions are wrapped as new Lua built-in functions. For example,
259 <div class="code"><pre>
261 int fact(int n);</pre></div>
263 creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
266 <div class="targetlang"><pre>
267 > print example.fact(4)
272 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.
274 <div class="targetlang"><pre>
275 > for k,v in pairs(example) do _G[k]=v end
281 It is also possible to rename the module with an assignment.
283 <div class="targetlang"><pre>
285 > print(e.fact(4))
287 > print(example.fact(4))
291 <H3><a name="Lua_nn10"></a>23.3.3 Global variables</H3>
295 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:
298 <div class="code"><pre>%module example
302 SWIG will effectively 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.
305 <div class="targetlang"><pre>
306 > print(example.Foo)
308 > c=example.Foo -- c is a COPY of example.Foo, not the same thing
312 > c=5 -- this will not effect the original example.Foo
313 > print(example.Foo,c)
317 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.
319 <div class="targetlang"><pre>
321 > -- e and example are the same table
322 > -- so e.Foo and example.Foo are the same thing
328 If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Lua error. Given a global variable:
331 <div class="code"><pre>%module example
337 SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
339 <div class="targetlang"><pre>
340 > print(e.Foo) -- reading works ok
342 > example.Foo=40 -- but writing does not
343 This variable is immutable
347 stdin:1: in main chunk
351 For those people who would rather that SWIG silently ignore the setting of immutables (as previous versions of the Lua bindings did), adding a <tt>-DSWIGLUA_IGNORE_SET_IMMUTABLE</tt> compile option will remove this.
354 Unlike earlier versions of the binding, it is now possible to add new functions or variables to the module, just as if it were a normal table. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.
356 <div class="targetlang"><pre>
357 > -- example.PI does not exist
358 > print(example.PI)
360 > example.PI=3.142 -- new value added
361 > print(example.PI)
365 <H3><a name="Lua_nn11"></a>23.3.4 Constants and enums</H3>
369 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:
371 <div class="code"><pre>%module example
372 %constant int ICONST=42;
373 #define SCONST "Hello World"
374 enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
377 This is 'effectively' converted into the following Lua code:
379 <div class="targetlang"><pre>
381 example.SCONST="Hello World"
386 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.
388 <H3><a name="Lua_nn12"></a>23.3.5 Pointers</H3>
392 C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:
394 <div class="code"><pre>%module example
396 FILE *fopen(const char *filename, const char *mode);
397 int fputs(const char *, FILE *);
401 When wrapped, you will be able to use the functions in a natural way from Lua. For example:
403 <div class="targetlang"><pre>
404 > f=example.fopen("junk","w")
405 > example.fputs("Hello World",f)
406 > example.fclose(f)
409 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).
411 <div class="targetlang"><pre>
414 > print(swig_type(f))
415 FILE * -- its a FILE*
418 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 & 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.
420 <div class="targetlang"><pre>
421 > f=example.fopen("not there","r") -- this will return a NULL in C
426 <H3><a name="Lua_nn13"></a>23.3.6 Structures</H3>
430 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,
432 <div class="code"><pre>struct Point{
439 <div class="targetlang"><pre>
440 > p=example.new_Point()
448 Similar access is provided for unions and the data members of C++ classes.<br>
449 C structures are created using a function <tt>new_Point()</tt>, but for C++ classes are created using just the name <tt>Point()</tt>.
452 If you print out the value of p in the above example, you will see something like this:
454 <div class="targetlang"><pre>
459 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 effectivly creates some accessor/mutator functions to get and set the data. These functions will be added to the userdata's metatable. This provides the natural access to the member variables that were shown above (see end of the document for full details).
462 <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 cause an error. For example:
464 <div class="code"><pre>struct Foo {
467 int x; // Read-only members
474 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).
477 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:
480 <div class="code"><pre>struct Foo {
489 Now, suppose that you access the f attribute of Bar like this:
491 <div class="targetlang"><pre>
496 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:
498 <div class="code"><pre>
500 Foo *x = &b->f; // Points inside b
503 Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
505 <div class="targetlang"><pre>
507 > b.f.a = 3 -- Modify attribute of structure member
509 > x.a = 3 -- Modifies the same structure
512 <H3><a name="Lua_nn14"></a>23.3.7 C++ classes</H3>
516 C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
518 <div class="code"><pre>class List {
522 int search(char *item);
523 void insert(char *item);
524 void remove(char *item);
530 you can use it in Lua like this:
532 <div class="targetlang"><pre>
533 > l = example.List()
535 > l:insert("Stout")
536 > l:insert("Lager")
544 (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. However for data attributes it is <tt>class.attribute</tt>)
547 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:
549 <div class="targetlang"><pre>class Spam {
557 In Lua, the static members can be accessed as follows:
559 <div class="code"><pre>
560 > example.Spam_foo() -- calling Spam::foo()
561 > a=example.Spam_bar -- reading Spam::bar
562 > example.Spam_bar=b -- writing to Spam::bar
565 It is not (currently) possible to access static members of an instance:
567 <div class="targetlang"><pre>
568 > s=example.Spam() -- s is a Spam instance
569 > s.foo() -- Spam::foo() via an instance
573 <H3><a name="Lua_nn15"></a>23.3.8 C++ inheritance</H3>
577 SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
579 <div class="code"><pre>class Foo {
583 class Bar : public Foo {
588 And if you have functions like this
590 <div class="code"><pre>void spam(Foo *f);
593 then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
596 It is safe to use multiple inheritance with SWIG.
598 <H3><a name="Lua_nn16"></a>23.3.9 Pointers, references, values, and arrays</H3>
602 In C++, there are many different ways a function might receive and manipulate objects. For example:
604 <div class="code"><pre>void spam1(Foo *x); // Pass by pointer
605 void spam2(Foo &x); // Pass by reference
606 void spam3(Foo x); // Pass by value
607 void spam4(Foo x[]); // Array of objects
610 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:
612 <div class="targetlang"><pre>
613 > f = Foo() -- Create a Foo
614 > spam1(f) -- Ok. Pointer
615 > spam2(f) -- Ok. Reference
616 > spam3(f) -- Ok. Value.
617 > spam4(f) -- Ok. Array (1 element)
620 Similar behaviour occurs for return values. For example, if you had functions like this,
622 <div class="code"><pre>Foo *spam5();
627 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.
629 <H3><a name="Lua_nn17"></a>23.3.10 C++ overloaded functions</H3>
633 C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
635 <div class="code"><pre>void foo(int);
639 You can use them in Lua in a straightforward manner:
641 <div class="targetlang"><pre>
642 > foo(3) -- foo(int)
643 > foo("Hello") -- foo(char *c)
646 However due to Lua's coercion mechanism is can sometimes do strange things.
648 <div class="targetlang"><pre>
649 > foo("3") -- "3" can be coerced into an int, so it calls foo(int)!
652 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).
655 Similarly, if you have a class like this,
657 <div class="code"><pre>class Foo {
660 Foo(const Foo &);
665 you can write Lua code like this:
667 <div class="targetlang"><pre>
668 > f = Foo() -- Create a Foo
669 > g = Foo(f) -- Copy f
672 Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
674 <div class="code"><pre>void spam(int);
680 <DIV CLASS="CODE"><PRE>VOID FOO(bAR *B);
681 void foo(Bar &b);
684 If declarations such as these appear, you will get a warning message like this:
686 <div class="shell"><pre>
687 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
691 To fix this, you either need to ignore or rename one of the methods. For example:
693 <div class="code"><pre>%rename(spam_short) spam(short);
696 void spam(short); // Accessed as spam_short
701 <div class="code"><pre>%ignore spam(short);
704 void spam(short); // Ignored
707 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.
710 Please refer to the "SWIG and C++" chapter for more information about overloading.
713 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.
715 <H3><a name="Lua_nn18"></a>23.3.11 C++ operators</H3>
719 Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
721 <div class="code"><pre>class Complex {
725 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
726 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
727 Complex &operator=(const Complex &c);
728 Complex operator+(const Complex &c) const;
729 Complex operator-(const Complex &c) const;
730 Complex operator*(const Complex &c) const;
731 Complex operator-() const;
733 double re() const { return rpart; }
734 double im() const { return ipart; }
738 When wrapped, it works like you expect:
740 <div class="targetlang"><pre>
741 > c = Complex(3,4)
742 > d = Complex(7,8)
750 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
752 <div class="targetlang"><pre>class Complex {
754 friend Complex operator+(double, const Complex &c);
759 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:
761 <div class="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &);
763 Complex operator+(double, const Complex &c);
766 There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
769 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>).
772 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).
774 The current list of operators which can be overloaded (and the alternative function names) are:<ul>
775 <li><tt>__add__</tt> operator+
776 <li><tt>__sub__</tt> operator-
777 <li><tt>__mul__</tt> operator *
778 <li><tt>__div__</tt> operator/
779 <li><tt>__neg__</tt> unary minus
780 <li><tt>__call__</tt> operator<tt>()</tt> (often used in functor classes)
781 <li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>^</tt>)
782 <li><tt>__concat__</tt> the concatenation operator (SWIG maps C++'s <tt>~</tt> to Lua's <tt>..</tt>)
783 <li><tt>__eq__</tt> operator<tt>==</tt>
784 <li><tt>__lt__</tt> operator<tt><</tt>
785 <li><tt>__le__</tt> operator<tt><=</tt>
788 Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=,>,>=) are achieved by using a logical not applied to the results of other operators.
791 The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
792 <li>++ and --<li>+=,-=,*= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
794 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
796 <div class="code"><pre>const char* __str__()
798 static char buffer[255];
799 sprintf(buffer,"Complex(%g,%g)",this->re(),this->im());
804 Then this will support the following code in Lua
806 <div class="targetlang"><pre>
807 > c = Complex(3,4)
808 > d = Complex(7,8)
812 > s=tostring(e) -- s is the number in string form
817 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>
819 <div class="code"><pre>class Complex
822 double __getitem__(int i)const; // i is the index, returns the data
823 void __setitem__(int i,double d); // i is the index, d is the data
827 <H3><a name="Lua_nn19"></a>23.3.12 Class extension with %extend</H3>
831 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.
834 Take the original Complex class
836 <div class="code"><pre>class Complex {
840 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
841 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
842 Complex &operator=(const Complex &c);
843 Complex operator+(const Complex &c) const;
844 Complex operator-(const Complex &c) const;
845 Complex operator*(const Complex &c) const;
846 Complex operator-() const;
848 double re() const { return rpart; }
849 double im() const { return ipart; }
853 Now we extend it with some new code
855 <div class="code"><pre>%extend Complex {
856 const char *__str__() {
857 static char tmp[1024];
858 sprintf(tmp,"Complex(%g,%g)", $self->re(),$self->im());
861 bool operator==(const Complex& c)
862 { return ($self->re()==c.re() && $self->im()==c.im();}
868 <div class="targetlang"><pre>
869 > c = Complex(3,4)
870 > d = Complex(7,8)
872 > print(e) -- print uses __str__ to get the string form to print
874 > print(e==Complex(10,12)) -- testing the == operator
876 > print(e!=Complex(12,12)) -- the != uses the == operator
880 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).
882 <H3><a name="Lua_nn20"></a>23.3.13 C++ templates</H3>
886 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:
888 <div class="code"><pre>%module example
893 template<class T1, class T2>
895 typedef T1 first_type;
896 typedef T2 second_type;
900 pair(const T1&, const T2&);
904 %template(pairii) pair<int,int>;
909 <div class="targetlang"><pre>
910 > p = example.pairii(3,4)
911 > print(p.first,p.second)
915 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.
917 <H3><a name="Lua_nn21"></a>23.3.14 C++ Smart Pointers</H3>
921 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->() like this:
923 <div class="code"><pre>template<class T> class SmartPtr {
930 Then, if you have a class like this,
932 <div class="code"><pre>class Foo {
939 A smart pointer would be used in C++ as follows:
941 <div class="code"><pre>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
943 p->x = 3; // Foo::x
944 int y = p->bar(); // Foo::bar
947 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:
949 <div class="code"><pre>%module example
951 %template(SmartPtrFoo) SmartPtr<Foo>;
955 Now, in Lua, everything should just "work":
957 <div class="targetlang"><pre>
958 > p = example.CreateFoo() -- Create a smart-pointer somehow
959 > p.x = 3 -- Foo::x
960 > print(p:bar()) -- Foo::bar
963 If you ever need to access the underlying pointer returned by <tt>operator->()</tt> itself, simply use the <tt>__deref__()</tt> method. For example:
965 <div class="targetlang"><pre>
966 > f = p:__deref__() -- Returns underlying Foo *
969 <H3><a name="Lua_nn22"></a>23.3.15 C++ Exceptions</H3>
973 Lua does not natively support exceptions, but it has errors which are similar. When a Lua function terminates with an error
974 it returns one value back to the caller. SWIG automatically maps any basic type which is thrown into a Lua error.
975 Therefore for a function:
977 <div class="code"><pre>
978 int message() throw(const char *) {
984 SWIG will automatically convert this to a Lua error.
987 <div class="targetlang"><pre>
991 [C]: in function 'message'
992 stdin:1: in main chunk
998 If you want to catch an exception, you must use either pcall() or xpcall(), which are documented in the Lua manual.
999 Using xpcall will allow you to obtain additional debug information (such as a stacktrace).
1002 <div class="targetlang"><pre>
1003 > function a() b() end -- function a() calls function b()
1004 > function b() message() end -- function b() calls C++ function message(), which throws
1005 > ok,res=pcall(a) -- call the function
1008 > ok,res=xpcall(a,debug.traceback) -- call the function
1012 [C]: in function 'message'
1013 runme.lua:70: in function 'b'
1014 runme.lua:67: in function <runme.lua:66>
1015 [C]: in function 'xpcall'
1016 runme.lua:95: in main chunk
1021 SWIG is able to throw numeric types, enums, chars, char*'s and std::string's without problem. It has also written typemaps for std::exception and its derived classes, which convert the exception into and error string. </p>
1023 However its not so simple for to throw other types of objects.
1024 Thrown objects are not valid outside the 'catch' block. Therefore they cannot be
1025 returned to the interpreter.
1026 The obvious ways to overcome this would be to either return a copy of the object, or so convert the object to a string and
1027 return that. Though it seems obvious to perform the former, in some cases this is not possible, most notably when
1028 SWIG has no information about the object, or the object is not copyable/creatable.
1031 Therefore by default SWIG converts all thrown object into strings and returns them. So given a function:
1034 <div class="code"><pre>
1035 void throw_A() throw(A*) {
1040 SWIG will just convert it (poorly) to a string and use that as its error. (Yes its not that useful, but it always works).
1043 <div class="targetlang"><pre>
1045 object exception:A *
1047 [C]: in function 'unknown'
1048 stdin:1: in main chunk
1053 To get a more useful behaviour out of SWIG you must either: provide a way to convert your exceptions into strings, or
1054 throw objects which can be copied.
1057 If you have your own class which you want output as a string you will need to add a typemap something like this:
1059 <div class="code"><pre>
1060 %typemap(throws) my_except
1062 lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
1063 SWIG_fail; // trigger the error handler
1067 If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have and additional
1068 <tt>%apply</tt> statement, to inform SWIG to return a copy of this object to the interpreter. For example:
1070 <div class="code"><pre>
1071 %apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
1075 Exc(int c, const char *m) {
1083 void throw_exc() throw(Exc) {
1084 throw(Exc(42,"Hosed"));
1088 Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
1090 <div class="targetlang"><pre>
1091 > ok,res=pcall(throw_exc)
1096 > print(res.code,res.msg)
1102 Note: is is also possible (though tedious) to have a function throw several different kinds of exceptions. To process this
1103 will require a pcall, followed by a set of if statements checking the type of the error.
1106 All of this code assumes that your C++ code uses exception specification (which a lot doesn't).
1107 If it doesn't consult the "<a href="SWIGPlus.html#SWIGPlus_catches">Exception handling with %catches</a>" section
1108 and the "<a href="Customization.html#exception">Exception handling with %exception</a>" section, for more details on how to
1109 add exception specification to functions or globally (respectively).
1113 <H2><a name="Lua_nn23"></a>23.4 Typemaps</H2>
1116 <p>This section explains what typemaps are and the usage of them. The default wrappering behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrappering. This section will be explaining how to use typemaps to best effect</p>
1118 <H3><a name="Lua_nn24"></a>23.4.1 What is a typemap?</H3>
1121 <p>A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:</p>
1123 <div class="code"><pre>%module example
1126 $1 = (int) lua_tonumber(L,$input);
1127 printf("Received an integer : %d\n",$1);
1130 extern int fact(int n);
1134 <p><i>Note: you shouldn't use this typemap, as SWIG already has a typemap for this task. This is purely for example.</i></p>
1136 <p>Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. The $input is the index on the Lua stack for the value to be used.</p>
1138 <p>When this example is compiled into a Lua module, it operates as follows:</p>
1140 <div class="targetlang"><pre>> require "example"
1141 > print(example.fact(6))
1142 Received an integer : 6
1146 <H3><a name="Lua_nn25"></a>23.4.2 Using typemaps</H3>
1149 <p>There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.</p>
1151 <p>However for more complex functions which use input/output parameters or arrays, you will need to make use of <typemaps.i>, which contains typemaps for these situations. For example, consider these functions:</p>
1153 <div class="code"><pre>void add(int x, int y, int *result) {
1157 int sub(int *x1, int *y1) {
1161 void swap(int *sx, int *sy) {
1168 <p>It is clear to the programmer, that 'result' is an output parameter, 'x1' and 'y1' are input parameters and 'sx' and 'sy' are input/output parameters. However is not apparent to SWIG, so SWIG must to informed about which kind they are, so it can wrapper accordingly.</p>
1170 <p>One means would be to rename the argument name to help SWIG, eg <tt>void add(int x, int y, int *OUTPUT)</tt>, however it is easier to use the <tt>%apply</tt> to achieve the same result, as shown below.</p>
1172 <div class="code"><pre>%include <typemaps.i>
1173 %apply int* OUTPUT {int *result}; // int *result is output
1174 %apply int* INPUT {int *x1, int *y1}; // int *x1 and int *y1 are input
1175 %apply int* INOUT {int *sx, int *sy}; // int *sx and int *sy are input and output
1177 void add(int x, int y, int *result);
1178 int sub(int *x1, int *y1);
1179 void swap(int *sx, int *sy);
1182 <p>When wrapped, it gives the following results:</p>
1184 <div class="targetlang"><pre>> require "example"
1185 > print(example.add(1,2))
1187 > print(demo.sub(1,2))
1190 > c,d=demo.swap(a,b)
1195 <p>Notice, that 'result' is not required in the arguments to call the function, as it an output parameter only. For 'sx' and 'sy' they must be passed in (as they are input), but the original value is not modified (Lua does not have a pass by reference feature). The modified results are then returned as two return values. All INPUT/OUTPUT/INOUT arguments will behave in a similar manner.</p>
1197 <p>Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a <tt>const int&</tt> as an input parameter (since that it obviously input).</p>
1199 <H3><a name="Lua_nn26"></a>23.4.3 Typemaps and arrays</H3>
1202 <p>Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor
1203 does SWIG have any indication of how large an array should be. However with the proper guidance SWIG can easily wrapper
1204 arrays for convenient usage.</p>
1206 <p>Given the functions:</p>
1207 <div class="code"><pre>extern void sort_int(int* arr, int len);
1208 extern void sort_double(double* arr, int len);
1211 <p>There are basically two ways that SWIG can deal with this. The first way, uses the <tt><carrays.i></tt> library
1212 to create an array in C/C++ then this can be filled within Lua and passed into the function. It works, but its a bit tedious.
1213 More details can be found in the <a href="Library.html#Library_nn5">carrays.i</a> documention.</p>
1215 <p>The second and more intuitive way, would be to pass a Lua table directly into the function, and have SWIG automatically convert between Lua-table and C-array. Within the <tt><typemaps.i></tt> file there are typemaps ready written to perform this task. To use them is again a matter of using %appy in the correct manner.</p>
1217 <p>The wrapper file below, shows both the use of carrays as well as the use of the typemap to wrap arrays. </p>
1219 <div class="code"><pre>// using the C-array
1220 %include <carrays.i>
1221 // this declares a batch of function for manipulating C integer arrays
1222 %array_functions(int,int)
1224 extern void sort_int(int* arr, int len); // the function to wrap
1227 %include <typemaps.i>
1228 %apply (double *INOUT,int) {(double* arr,int len)};
1230 extern void sort_double(double* arr, int len); // the function to wrap
1233 <p>Once wrappered, the functions can both be called, though with different ease of use:</p>
1235 <div class="targetlang"><pre>require "example"
1238 -- passing a C array to the sort_int()
1239 arr=example.new_int(ARRAY_SIZE) -- create the array
1240 for i=0,ARRAY_SIZE-1 do -- index 0..9 (just like C)
1241 example.int_setitem(arr,i,math.random(1000))
1243 example.sort_int(arr,ARRAY_SIZE) -- call the function
1244 example.delete_int(arr) -- must delete the allocated memory
1246 -- use a typemap to call with a Lua-table
1247 -- one item of note: the typemap creates a copy, rather than edit-in-place
1249 for i=1,ARRAY_SIZE do -- index 1..10 (Lua style)
1250 t[i]=math.random(1000)/10
1252 t=example.sort_double(t) -- replace t with the result
1255 <p>Obviously the first version could be made less tedious by writing a Lua function to perform the conversion from a table
1256 to a C-array. The <tt>%luacode</tt> directive is good for this. See SWIG\Examples\lua\arrays for an example of this.</p>
1258 <p><b>Warning:</b> in C indexes start at ZERO, in Lua indexes start at ONE. SWIG expects C-arrays to be filled for 0..N-1
1259 and Lua tables to be 1..N, (the indexing follows the norm for the language). In the typemap when it converts the table to an array it quietly changes the indexing accordingly. Take note of this behaviour if you have a C function which returns indexes.</p>
1261 <p>Note: SWIG also can support arrays of pointers in a similar manner.</p>
1263 <H3><a name="Lua_nn27"></a>23.4.4 Typemaps and pointer-pointer functions</H3>
1266 <p>Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:</p>
1268 <div class="code"><pre>struct iMath; // some structure
1269 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
1272 <p>Which would be used with the following C code:</p>
1274 <div class="code"><pre>iMath* ptr;
1276 ok=Create_Math(&ptr);
1277 // do things with ptr
1279 free(ptr); // dispose of iMath
1282 <p>SWIG has a ready written typemap to deal with such a kind of function in <typemaps.i>. It provides the correct wrappering as well as setting the flag to inform Lua that the object in question should be garbage collected. Therefore the code is simply:</p>
1284 <div class="code"><pre>%include <typemaps.i>
1285 %apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG its an output
1287 struct iMath; // some structure
1288 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
1291 <p>The usage is as follows:</p>
1293 <div class="targetlang"><pre>ok,ptr=Create_Math() -- ptr is a iMath* which is returned with the int (ok)
1294 ptr=nil -- the iMath* will be GC'ed as normal
1297 <H2><a name="Lua_nn28"></a>23.5 Writing typemaps</H2>
1300 <p>This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the <tt>%typemap</tt> directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.</p>
1302 <p>Before proceeding, it should be stressed that writing typemaps is rarely needed unless you want to change some aspect of the wrappering, or to achieve an effect which in not available with the default bindings.</p>
1304 <p>Before proceeding, you should read the previous section on using typemaps, as well as read the ready written typemaps found in luatypemaps.swg and typemaps.i. These are both well documented and fairly easy to read. You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you a idea to base your worn on).</p>
1306 <H3><a name="Lua_nn29"></a>23.5.1 Typemaps you can write</H3>
1309 <p>There are many different types of typemap that can be written, the full list can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter. However the following are the most commonly used ones.</p>
1312 <li><tt>in</tt> this is for input arguments to functions</li>
1313 <li><tt>out</tt> this is for return types from functions</li>
1314 <li><tt>argout</tt> this is for a function argument which is actually returning something</li>
1315 <li><tt>typecheck</tt> this is used to determine which overloaded function should be called
1316 (the syntax for the typecheck is different from the typemap, see typemaps for details).</li>
1319 <H3><a name="Lua_nn30"></a>23.5.2 SWIG's Lua-C API</H3>
1322 <p>This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.</p>
1324 <p><tt>int SWIG_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags);</tt></p>
1326 <div class="indent">
1327 This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the neccesary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer.
1328 If flags is set to SWIG_POINTER_DISOWN, this is will clear any ownership flag set on the object.<br>
1329 The returns a value which can be checked with the macro SWIG_IsOK()
1332 <p><tt>void SWIG_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type,int own);</tt></p>
1334 <div class="indent">
1335 This is the opposite of SWIG_ConvertPtr, as it pushes a new userdata which wrappers the pointer 'ptr' of type 'type'.
1336 The parameter 'own' specifies if the object is owned be Lua and if it is 1 then Lua will GC the object when the userdata is disposed of.
1339 <p><tt>void* SWIG_MustGetPtr(lua_State* L,int index,swig_type_info *type,int flags,int argnum,const char* func_name);</tt></p>
1341 <div class="indent">
1342 This function is a version of SWIG_ConvertPtr(), except that it will either work, or it will trigger a lua_error() with a text error message. This function is rarely used, and may be deprecated in the future.
1345 <p><tt>SWIG_fail</tt></p>
1347 <div class="indent">
1348 This macro, when called within the context of a SWIG wrappered function, will jump to the error handler code. This will call any cleanup code (freeing any temp variables) and then triggers a lua_error.<br>
1349 A common use for this code is:<br><pre>
1350 if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
1351 lua_pushstring(L,"something bad happened");
1355 <p><tt>SWIG_fail_arg(char* func_name,int argnum,char* type)</tt></p>
1357 <div class="indent">
1358 This macro, when called within the context of a SWIG wrappered function, will display the error message and jump to the error handler code. The error message is of the form
1360 "Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'"
1363 <p><tt>SWIG_fail_ptr(const char* fn_name,int argnum,swig_type_info* type);</tt></p>
1365 <div class="indent">
1366 Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.</div>
1368 <H2><a name="Lua_nn31"></a>23.6 Customization of your Bindings</H2>
1372 This section covers adding of some small extra bits to your module to add the last finishing touches.
1377 <H3><a name="Lua_nn32"></a>23.6.1 Writing your own custom wrappers</H3>
1381 Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native Lua API calls. These 'native' functions allow direct adding of your own code into the module. This is performed with the <tt>%native</tt> directive as follows:
1383 <div class="code"><pre>%native(my_func) int native_function(lua_State*L); // registers native_function() with SWIG
1386 int native_function(lua_State*L) // my native code
1393 The <tt>%native</tt> directive in the above example, tells SWIG that there is a function <tt>int native_function(lua_State*L);</tt> which is to be added into the module under the name '<tt>my_func</tt>'. SWIG will not add any wrappering for this function, beyond adding it into the function table. How you write your code is entirely up to you.
1396 <H3><a name="Lua_nn33"></a>23.6.2 Adding additional Lua code</H3>
1400 As well as adding additional C/C++ code, its also possible to add your own Lua code to the module as well.
1401 This code is executed once all other initialisation, including the %init code has been called.
1404 The directive <tt>%luacode</tt> adds code into the module which is executed upon loading. Normally you would
1405 use this to add your own functions to the module. Though you could easily perform other tasks.
1407 <div class="code"><pre>%module example;
1410 function example.greet()
1414 print "Module loaded ok"
1420 Notice that the code is not part of the module table. Therefore any references to the module must have the
1424 Should there be an error in the Lua code, this will <em>not</em> stop loading of the module.
1425 The default behaviour of SWIG is to print a error message to stderr and then continue.
1426 It is possible to change this behaviour by using a <tt>#define SWIG_DOSTRING_FAIL(STR)</tt> to
1427 define a different behaviour should the code fail.
1430 Good uses for this feature is adding of new code, or writing helper functions to simplify some of the code.
1431 See Examples/lua/arrays for an example of this code.
1434 <H2><a name="Lua_nn34"></a>23.7 Details on the Lua binding</H2>
1438 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.
1441 <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.
1445 <H3><a name="Lua_nn35"></a>23.7.1 Binding global data into the module.</H3>
1449 Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
1451 <div class="code"><pre>%module example;
1455 SWIG will effectively generate the pair of functions
1457 <div class="code"><pre>void Foo_set(double);
1461 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. (Note: older versions of SWIG actually added the Foo_set() and Foo_get() functions, current implementation does not add these functions any more.) 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.
1463 <div class="targetlang"><pre>
1466 > m=getmetatable(example)
1467 > table.foreach(m,print)
1468 .set table: 003F9088
1469 .get table: 003F9038
1470 __index function: 003F8FE0
1471 __newindex function: 003F8FF8
1473 > table.foreach(g,print)
1474 Foo function: 003FAFD8
1478 The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)
1481 The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
1483 <div class="targetlang"><pre>
1484 function __index(mod,name)
1485 local g=getmetatable(mod)['.get'] -- gets the table
1486 if not g then return nil end
1487 local f=g[name] -- looks for the function
1488 -- calls it & returns the value
1489 if type(f)=="function" then return f() end
1493 function __newindex(mod,name,value)
1494 local s=getmetatable(mod)['.set'] -- gets the table
1495 if not s then return end
1496 local f=s[name] -- looks for the function
1497 -- calls it to set the value
1498 if type(f)=="function" then f(value)
1499 else rawset(mod,name,value) end
1503 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)'.
1505 <H3><a name="Lua_nn36"></a>23.7.2 Userdata and Metatables</H3>
1509 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.
1512 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.
1517 <div class="code"><pre>%module excpp;
1525 virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
1529 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.
1532 Some of the internals can be seen by looking at a classes metatable.
1534 <div class="targetlang"><pre>
1535 > p=excpp.Point()
1538 > m=getmetatable(p)
1539 > table.foreach(m,print)
1541 __gc function: 003FB6C8
1542 __newindex function: 003FB6B0
1543 __index function: 003FB698
1544 .get table: 003FB4D8
1545 .set table: 003FB500
1549 The '.type' attribute is the name of the class. 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)
1552 The Lua equivalent of the code for enabling functions looks a little like this
1554 <div class="targetlang"><pre>
1555 function __index(obj,name)
1556 local m=getmetatable(obj) -- gets the metatable
1557 if not m then return nil end
1558 local g=m['.get'] -- gets the attribute table
1559 if not g then return nil end
1560 local f=g[name] -- looks for the get_attribute function
1561 -- calls it & returns the value
1562 if type(f)=="function" then return f() end
1563 -- ok, so it not an attribute, maybe its a function
1564 local fn=m['.fn'] -- gets the function table
1565 if not fn then return nil end
1566 local f=fn[name] -- looks for the function
1567 -- if found the fn then return the function
1568 -- so the interpreter can call it
1569 if type(f)=="function" then return f end
1574 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)'
1577 In theory, you can play with this usertable & 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.
1580 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.
1583 Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__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.
1585 <H3><a name="Lua_nn37"></a>23.7.3 Memory management</H3>
1589 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 & 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.
1592 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.
1595 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)