import source from 1.3.40
[external/swig.git] / Doc / Manual / Lua.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>SWIG and Lua</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
6 </head>
7
8 <body bgcolor="#ffffff">
9 <H1><a name="Lua_nn1"></a>23 SWIG and Lua</H1>
10 <!-- INDEX -->
11 <div class="sectiontoc">
12 <ul>
13 <li><a href="#Lua_nn2">Preliminaries</a>
14 <li><a href="#Lua_nn3">Running SWIG</a>
15 <ul>
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>
19 </ul>
20 <li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
21 <ul>
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>
37 </ul>
38 <li><a href="#Lua_nn23">Typemaps</a>
39 <ul>
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>
44 </ul>
45 <li><a href="#Lua_nn28">Writing typemaps</a>
46 <ul>
47 <li><a href="#Lua_nn29">Typemaps you can write</a>
48 <li><a href="#Lua_nn30">SWIG's Lua-C API</a>
49 </ul>
50 <li><a href="#Lua_nn31">Customization of your Bindings</a>
51 <ul>
52 <li><a href="#Lua_nn32">Writing your own custom wrappers</a>
53 <li><a href="#Lua_nn33">Adding additional Lua code</a>
54 </ul>
55 <li><a href="#Lua_nn34">Details on the Lua binding</a>
56 <ul>
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>
60 </ul>
61 </ul>
62 </div>
63 <!-- INDEX -->
64
65
66
67 <p>
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 &lt;100 kilobytes of binary code. It can be found at <a href="http://www.lua.org">http://www.lua.org</a>
69 </p>
70 <H2><a name="Lua_nn2"></a>23.1 Preliminaries</H2>
71
72
73 <p>
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).
75 </p>
76 <H2><a name="Lua_nn3"></a>23.2 Running SWIG</H2>
77
78
79 <p>
80 Suppose that you defined a SWIG module such as the following:
81 </p>
82 <div class="code"><pre>
83 %module example
84 %{
85 #include "example.h"
86 %}
87 int gcd(int x, int y);
88 extern double Foo;
89 </pre></div>
90 <p>
91 To build a Lua module, run SWIG using the <tt>-lua</tt> option.
92 </p>
93 <div class="shell"><pre>
94 $ swig -lua example.i
95 </pre></div>
96 <p>
97 If building a C++ extension, add the <tt>-c++</tt> option:
98 </p>
99 <div class="shell"><pre>
100 $ swig -c++ -lua example.i
101 </pre></div>
102 <p>
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.
104 </p>
105 <p>
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.
107 </p>
108 <H3><a name="Lua_nn4"></a>23.2.1 Compiling and Linking and Interpreter</H3>
109
110
111 <p>
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:
113 </p>
114 <div class="code"><pre>
115 #include &lt;stdio.h&gt;
116 #include "lua.h"
117 #include "lualib.h"
118 #include "lauxlib.h"
119
120 extern int luaopen_example(lua_State* L); // declare the wrapped module
121
122 int main(int argc,char* argv[])
123 {
124  lua_State *L;
125  if (argc&lt;2)
126  {
127   printf("%s: &lt;filename.lua&gt;\n",argv[0]);
128   return 0;
129  }
130  L=lua_open();
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
134   lua_pcall(L,0,0,0);
135  else
136   printf("unable to load %s\n",argv[1]);
137  lua_close(L);
138  return 0;
139 }
140 </pre></div>
141 <p>
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 &amp; add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place.
143 </p>
144 <p>
145 The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
146 </p>
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
153 </pre></div>
154
155 <H3><a name="Lua_nn5"></a>23.2.2 Compiling a dynamic module</H3>
156
157
158 <p>
159 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:
160 </p>
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
166 </pre></div>
167 <p>
168 The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x. The loading is extremely simple.
169 </p>
170 <div class="targetlang"><pre>
171 require("example")
172 </pre></div>
173 <p>
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
175 </p>
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
181 </pre></div>
182 <p>
183 Or can be done in a single line of Lua code
184 </p>
185 <div class="targetlang"><pre>
186 assert(loadlib("example.so","luaopen_example"))()
187 </pre></div>
188
189
190 <p>
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).
192 </p>
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
196 print(a,b,c)
197 </pre></div>
198 <p>
199 Note: for Lua 5.0:<br>
200 The loadlib() function is in the global namespace, not in package. So its just loadlib().
201 </p>
202 <p>
203 if 'a' is a function, this its all working fine, all you need to do is call it
204 </p>
205 <div class="targetlang"><pre>
206   a()
207 </pre></div>
208 <p>
209 to load your library which will add a table 'example' with all the functions added.
210 </p>
211 <p>
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).
219 </p>
220
221
222
223 <H3><a name="Lua_nn6"></a>23.2.3 Using your module</H3>
224
225
226 <p>
227 Assuming all goes well, you will be able to this:
228 </p>
229 <div class="targetlang"><pre>
230 $ ./my_lua
231 &gt; print(example.gcd(4,6))
232 2
233 &gt; print(example.Foo)
234 3
235 &gt; example.Foo=4
236 &gt; print(example.Foo)
237 4
238 &gt;
239 </pre></div>
240
241 <H2><a name="Lua_nn7"></a>23.3 A tour of basic C/C++ wrapping</H2>
242
243
244 <p>
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.
246 </p>
247 <H3><a name="Lua_nn8"></a>23.3.1 Modules</H3>
248
249
250 <p>
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.
252 </p>
253 <H3><a name="Lua_nn9"></a>23.3.2 Functions</H3>
254
255
256 <p>
257  Global functions are wrapped as new Lua built-in functions. For example,
258 </p>
259 <div class="code"><pre>
260 %module example
261 int fact(int n);</pre></div>
262 <p>
263 creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
264 </p>
265
266 <div class="targetlang"><pre>
267 &gt; print example.fact(4)
268 24
269 &gt;
270 </pre></div>
271 <p>
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.
273 </p>
274 <div class="targetlang"><pre>
275 &gt; for k,v in pairs(example) do _G[k]=v end
276 &gt; print(fact(4))
277 24
278 &gt;
279 </pre></div>
280 <p>
281 It is also possible to rename the module with an assignment.
282 </p>
283 <div class="targetlang"><pre>
284 &gt; e=example
285 &gt; print(e.fact(4))
286 24
287 &gt; print(example.fact(4))
288 24
289 </pre></div>
290
291 <H3><a name="Lua_nn10"></a>23.3.3 Global variables</H3>
292
293
294 <p>
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:
296 </p>
297
298 <div class="code"><pre>%module example
299 extern double Foo;
300 </pre></div>
301 <p>
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.
303 </p>
304
305 <div class="targetlang"><pre>
306 &gt; print(example.Foo)
307 3
308 &gt; c=example.Foo   -- c is a COPY of example.Foo, not the same thing
309 &gt; example.Foo=4
310 &gt; print(c)
311 3
312 &gt; c=5 -- this will not effect the original example.Foo
313 &gt; print(example.Foo,c)
314 4    5
315 </pre></div>
316 <p>
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.
318 </p>
319 <div class="targetlang"><pre>
320 &gt; e=example
321 &gt; -- e and example are the same table
322 &gt; -- so e.Foo and example.Foo are the same thing
323 &gt; example.Foo=4
324 &gt; print(e.Foo)
325 4
326 </pre></div>
327 <p>
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:
329 </p>
330
331 <div class="code"><pre>%module example
332 %immutable;
333 extern double Foo;
334 %mutable;
335 </pre></div>
336 <p>
337 SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
338 </p>
339 <div class="targetlang"><pre>
340 &gt; print(e.Foo) -- reading works ok
341 4
342 &gt; example.Foo=40 -- but writing does not
343 This variable is immutable
344 stack traceback:
345         [C]: ?
346         [C]: ?
347         stdin:1: in main chunk
348         [C]: ?
349 </pre></div>
350 <p>
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.
352 </p>
353 <p>
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.
355 </p>
356 <div class="targetlang"><pre>
357 &gt; -- example.PI does not exist
358 &gt; print(example.PI)
359 nil
360 &gt; example.PI=3.142 -- new value added
361 &gt; print(example.PI)
362 3.142
363 </pre></div>
364
365 <H3><a name="Lua_nn11"></a>23.3.4 Constants and enums</H3>
366
367
368 <p>
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:
370 </p>
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};
375 </pre></div>
376 <p>
377 This is 'effectively' converted into the following Lua code:
378 </p>
379 <div class="targetlang"><pre>
380 example.ICONST=42
381 example.SCONST="Hello World"
382 example.SUNDAY=0
383 ....
384 </pre></div>
385 <p>
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.
387 </p>
388 <H3><a name="Lua_nn12"></a>23.3.5 Pointers</H3>
389
390
391 <p>
392 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:
393 </p>
394 <div class="code"><pre>%module example
395
396 FILE *fopen(const char *filename, const char *mode);
397 int fputs(const char *, FILE *);
398 int fclose(FILE *);
399 </pre></div>
400 <p>
401 When wrapped, you will be able to use the functions in a natural way from Lua. For example:
402 </p>
403 <div class="targetlang"><pre>
404 &gt; f=example.fopen("junk","w")
405 &gt; example.fputs("Hello World",f)
406 &gt; example.fclose(f)
407 </pre></div>
408 <p>
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).
410 </p>
411 <div class="targetlang"><pre>
412 &gt; print(f)
413 userdata: 003FDA80
414 &gt; print(swig_type(f))
415 FILE * -- its a FILE*
416 </pre></div>
417 <p>
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 &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.
419 </p>
420 <div class="targetlang"><pre>
421 &gt; f=example.fopen("not there","r") -- this will return a NULL in C
422 &gt; print(f)
423 nil
424 </pre></div>
425
426 <H3><a name="Lua_nn13"></a>23.3.6 Structures</H3>
427
428
429 <p>
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,
431 </p>
432 <div class="code"><pre>struct Point{
433   int x,y;
434 };
435 </pre></div>
436 <p>
437 is used as follows:
438 </p>
439 <div class="targetlang"><pre>
440 &gt; p=example.new_Point()
441 &gt; p.x=3
442 &gt; p.y=5
443 &gt; print(p.x,p.y)
444 3       5
445 &gt;
446 </pre></div>
447 <p>
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>.
450 </p>
451 <p>
452 If you print out the value of p in the above example, you will see something like this:
453 </p>
454 <div class="targetlang"><pre>
455 &gt; print(p)
456 userdata: 003FA320
457 </pre></div>
458 <p>
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).
460 </p>
461 <p>
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:
463 </p>
464 <div class="code"><pre>struct Foo {
465    ...
466    %immutable;
467    int x;        // Read-only members
468    char *name;
469    %mutable;
470    ...
471 };
472 </pre></div>
473 <p>
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).
475 </p>
476 <p>
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:
478 </p>
479
480 <div class="code"><pre>struct Foo {
481    int a;
482 };
483
484 struct Bar {
485    Foo f;
486 };
487 </pre></div>
488 <p>
489 Now, suppose that you access the f attribute of Bar like this:
490 </p>
491 <div class="targetlang"><pre>
492 &gt; b = Bar()
493 &gt; x = b.f
494 </pre></div>
495 <p>
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:
497 </p>
498 <div class="code"><pre>
499 Bar b;
500 Foo *x = &amp;b-&gt;f;       // Points inside b
501 </pre></div>
502 <p>
503 Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
504 </p>
505 <div class="targetlang"><pre>
506 &gt; b = Bar()
507 &gt; b.f.a = 3               -- Modify attribute of structure member
508 &gt; x = b.f
509 &gt; x.a = 3                 -- Modifies the same structure
510 </pre></div>
511
512 <H3><a name="Lua_nn14"></a>23.3.7 C++ classes</H3>
513
514
515 <p>
516 C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
517 </p>
518 <div class="code"><pre>class List {
519 public:
520   List();
521   ~List();
522   int  search(char *item);
523   void insert(char *item);
524   void remove(char *item);
525   char *get(int n);
526   int  length;
527 };
528 </pre></div>
529 <p>
530 you can use it in Lua like this:
531 </p>
532 <div class="targetlang"><pre>
533 &gt; l = example.List()
534 &gt; l:insert("Ale")
535 &gt; l:insert("Stout")
536 &gt; l:insert("Lager")
537 &gt; print(l:get(1))
538 Stout
539 &gt; print(l:length)
540 3
541 &gt;
542 </pre></div>
543 <p>
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>)
545 </p>
546 <p>
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:
548 </p>
549 <div class="targetlang"><pre>class Spam {
550 public:
551    static void foo();
552    static int bar;
553
554 };
555 </pre></div>
556 <p>
557 In Lua, the static members can be accessed as follows:
558 </p>
559 <div class="code"><pre>
560 &gt; example.Spam_foo()            -- calling Spam::foo()
561 &gt; a=example.Spam_bar            -- reading Spam::bar 
562 &gt; example.Spam_bar=b            -- writing to Spam::bar
563 </pre></div>
564 <p>
565 It is not (currently) possible to access static members of an instance:
566 </p>
567 <div class="targetlang"><pre>
568 &gt; s=example.Spam()      -- s is a Spam instance
569 &gt; s.foo()                       -- Spam::foo() via an instance
570                                 -- does NOT work
571 </pre></div>
572
573 <H3><a name="Lua_nn15"></a>23.3.8 C++ inheritance</H3>
574
575
576 <p>
577 SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
578 </p>
579 <div class="code"><pre>class Foo {
580 ...
581 };
582
583 class Bar : public Foo {
584 ...
585 };
586 </pre></div>
587 <p>
588 And if you have functions like this
589 </p>
590 <div class="code"><pre>void spam(Foo *f);
591 </pre></div>
592 <p>
593 then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
594 </p>
595 <p>
596 It is safe to use multiple inheritance with SWIG.
597 </p>
598 <H3><a name="Lua_nn16"></a>23.3.9 Pointers, references, values, and arrays</H3>
599
600
601 <p>
602 In C++, there are many different ways a function might receive and manipulate objects. For example:
603 </p>
604 <div class="code"><pre>void spam1(Foo *x);      // Pass by pointer
605 void spam2(Foo &amp;x);      // Pass by reference
606 void spam3(Foo x);       // Pass by value
607 void spam4(Foo x[]);     // Array of objects
608 </pre></div>
609 <p>
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:
611 </p>
612 <div class="targetlang"><pre>
613 &gt; f = Foo()           -- Create a Foo
614 &gt; spam1(f)            -- Ok. Pointer
615 &gt; spam2(f)            -- Ok. Reference
616 &gt; spam3(f)            -- Ok. Value.
617 &gt; spam4(f)            -- Ok. Array (1 element)
618 </pre></div>
619 <p>
620 Similar behaviour occurs for return values. For example, if you had functions like this,
621 </p>
622 <div class="code"><pre>Foo *spam5();
623 Foo &amp;spam6();
624 Foo  spam7();
625 </pre></div>
626 <p>
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.
628 </p>
629 <H3><a name="Lua_nn17"></a>23.3.10 C++ overloaded functions</H3>
630
631
632 <p>
633 C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
634 </p>
635 <div class="code"><pre>void foo(int);
636 void foo(char *c);
637 </pre></div>
638 <p>
639 You can use them in Lua in a straightforward manner:
640 </p>
641 <div class="targetlang"><pre>
642 &gt; foo(3)           -- foo(int)
643 &gt; foo("Hello")     -- foo(char *c)
644 </pre></div>
645 <p>
646 However due to Lua's coercion mechanism is can sometimes do strange things.
647 </p>
648 <div class="targetlang"><pre>
649 &gt; foo("3")           -- "3" can be coerced into an int, so it calls foo(int)!
650 </pre></div>
651 <p>
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).
653 </p>
654 <p>
655 Similarly, if you have a class like this,
656 </p>
657 <div class="code"><pre>class Foo {
658 public:
659     Foo();
660     Foo(const Foo &amp;);
661     ...
662 };
663 </pre></div>
664 <p>
665 you can write Lua code like this:
666 </p>
667 <div class="targetlang"><pre>
668 &gt; f = Foo()          -- Create a Foo
669 &gt; g = Foo(f)         -- Copy f
670 </pre></div>
671 <p>
672 Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
673 </p>
674 <div class="code"><pre>void spam(int);
675 void spam(short);
676 </pre></div>
677 <p>
678 or
679 </p>
680 <DIV CLASS="CODE"><PRE>VOID FOO(bAR *B);
681 void foo(Bar &amp;b);
682 </pre></div>
683 <p>
684 If declarations such as these appear, you will get a warning message like this:
685 </p>
686 <div class="shell"><pre>
687 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
688 at example.i:11.
689 </pre></div>
690 <p>
691  To fix this, you either need to ignore or rename one of the methods. For example:
692 </p>
693 <div class="code"><pre>%rename(spam_short) spam(short);
694 ...
695 void spam(int);
696 void spam(short);   // Accessed as spam_short
697 </pre></div>
698 <p>
699 or
700 </p>
701 <div class="code"><pre>%ignore spam(short);
702 ...
703 void spam(int);
704 void spam(short);   // Ignored
705 </pre></div>
706 <p>
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.
708 </p>
709 <p>
710 Please refer to the "SWIG and C++" chapter for more information about overloading.
711 </p>
712 <p>
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.
714 </p>
715 <H3><a name="Lua_nn18"></a>23.3.11 C++ operators</H3>
716
717
718 <p>
719 Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
720 </p>
721 <div class="code"><pre>class Complex {
722 private:
723   double rpart, ipart;
724 public:
725   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
726   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
727   Complex &amp;operator=(const Complex &amp;c);
728   Complex operator+(const Complex &amp;c) const;
729   Complex operator-(const Complex &amp;c) const;
730   Complex operator*(const Complex &amp;c) const;
731   Complex operator-() const;
732
733   double re() const { return rpart; }
734   double im() const { return ipart; }
735 };
736 </pre></div>
737 <p>
738 When wrapped, it works like you expect:
739 </p>
740 <div class="targetlang"><pre>
741 &gt; c = Complex(3,4)
742 &gt; d = Complex(7,8)
743 &gt; e = c + d
744 &gt; e:re()
745 10.0
746 &gt; e:im()
747 12.0
748 </pre></div>
749 <p>
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
751 </p>
752 <div class="targetlang"><pre>class Complex {
753 ...
754 friend Complex operator+(double, const Complex &amp;c);
755 ...
756 };
757 </pre></div>
758 <p>
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:
760 </p>
761 <div class="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &amp;);
762 ...
763 Complex operator+(double, const Complex &amp;c);
764 </pre></div>
765 <p>
766 There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
767 </p>
768 <p>
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>).
770 </p>
771 <p>
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).
773 <p>
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>&lt;</tt>
785 <li><tt>__le__</tt> operator<tt>&lt;=</tt>
786 </ul>
787 <p>
788 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.
789 </p>
790 <p>
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>
793 <p>
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
795 </p>
796 <div class="code"><pre>const char* __str__()
797 {
798         static char buffer[255];
799         sprintf(buffer,"Complex(%g,%g)",this-&gt;re(),this-&gt;im());
800         return buffer;
801 }
802 </pre></div>
803 <p>
804 Then this will support the following code in Lua
805 </p>
806 <div class="targetlang"><pre>
807 &gt; c = Complex(3,4)
808 &gt; d = Complex(7,8)
809 &gt; e = c + d
810 &gt; print(e)
811 Complex(10,12)
812 &gt; s=tostring(e) -- s is the number in string form
813 &gt; print(s)
814 Complex(10,12)
815 </pre></div>
816 <p>
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>
818 </p>
819 <div class="code"><pre>class Complex
820 {
821         //....
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
824 };
825 </pre></div>
826
827 <H3><a name="Lua_nn19"></a>23.3.12 Class extension with %extend</H3>
828
829
830 <p>
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.
832 </p>
833 <p>
834 Take the original Complex class
835 </p>
836 <div class="code"><pre>class Complex {
837 private:
838   double rpart, ipart;
839 public:
840   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
841   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
842   Complex &amp;operator=(const Complex &amp;c);
843   Complex operator+(const Complex &amp;c) const;
844   Complex operator-(const Complex &amp;c) const;
845   Complex operator*(const Complex &amp;c) const;
846   Complex operator-() const;
847
848   double re() const { return rpart; }
849   double im() const { return ipart; }
850 };
851 </pre></div>
852 <p>
853 Now we extend it with some new code
854 </p>
855 <div class="code"><pre>%extend Complex {
856    const char *__str__() {
857        static char tmp[1024];
858        sprintf(tmp,"Complex(%g,%g)", $self-&gt;re(),$self-&gt;im());
859        return tmp;
860    }
861    bool operator==(const Complex&amp; c)
862    {    return ($self-&gt;re()==c.re() &amp;&amp; $self-&gt;im()==c.im();}
863 };
864 </pre></div>
865 <p>
866 Now, in Lua
867 </p>
868 <div class="targetlang"><pre>
869 &gt; c = Complex(3,4)
870 &gt; d = Complex(7,8)
871 &gt; e = c + d
872 &gt; print(e)      -- print uses __str__ to get the string form to print
873 Complex(10,12)
874 &gt; print(e==Complex(10,12))      -- testing the == operator
875 true
876 &gt; print(e!=Complex(12,12))  -- the != uses the == operator
877 true
878 </pre></div>
879 <p>
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).
881 </p>
882 <H3><a name="Lua_nn20"></a>23.3.13 C++ templates</H3>
883
884
885 <p>
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:
887 </p>
888 <div class="code"><pre>%module example
889 %{
890 #include "pair.h"
891 %}
892
893 template&lt;class T1, class T2&gt;
894 struct pair {
895    typedef T1 first_type;
896    typedef T2 second_type;
897    T1 first;
898    T2 second;
899    pair();
900    pair(const T1&amp;, const T2&amp;);
901   ~pair();
902 };
903
904 %template(pairii) pair&lt;int,int&gt;;
905 </pre></div>
906 <p>
907 In Lua:
908 </p>
909 <div class="targetlang"><pre>
910 &gt; p = example.pairii(3,4)
911 &gt; print(p.first,p.second)
912 3    4
913 </pre></div>
914 <p>
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.
916 </p>
917 <H3><a name="Lua_nn21"></a>23.3.14 C++ Smart Pointers</H3>
918
919
920 <p>
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-&gt;() like this:
922 </p>
923 <div class="code"><pre>template&lt;class T&gt; class SmartPtr {
924    ...
925    T *operator-&gt;();
926    ...
927 }
928 </pre></div>
929 <p>
930 Then, if you have a class like this,
931 </p>
932 <div class="code"><pre>class Foo {
933 public:
934      int x;
935      int bar();
936 };
937 </pre></div>
938 <p>
939 A smart pointer would be used in C++ as follows:
940 </p>
941 <div class="code"><pre>SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
942 ...
943 p-&gt;x = 3;                        // Foo::x
944 int y = p-&gt;bar();                // Foo::bar
945 </pre></div>
946 <p>
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:
948 </p>
949 <div class="code"><pre>%module example
950 ...
951 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
952 ...
953 </pre></div>
954 <p>
955 Now, in Lua, everything should just "work":
956 </p>
957 <div class="targetlang"><pre>
958 &gt; p = example.CreateFoo()          -- Create a smart-pointer somehow
959 &gt; p.x = 3                          -- Foo::x
960 &gt; print(p:bar())                   -- Foo::bar
961 </pre></div>
962 <p>
963 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:
964 </p>
965 <div class="targetlang"><pre>
966 &gt; f = p:__deref__()     -- Returns underlying Foo *
967 </pre></div>
968
969 <H3><a name="Lua_nn22"></a>23.3.15 C++ Exceptions</H3>
970
971
972 <p>
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:
976 </p>
977 <div class="code"><pre>
978 int message() throw(const char *) {
979   throw("I died.");
980   return 1;
981 }
982 </pre></div>
983 <p>
984 SWIG will automatically convert this to a Lua error.
985 </p>
986
987 <div class="targetlang"><pre>
988 > message()
989 I died.
990 stack traceback:
991         [C]: in function 'message'
992         stdin:1: in main chunk
993         [C]: ?
994 >
995 </pre></div>
996
997 <p>
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).
1000 </p>
1001
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
1006 > print(ok,res)
1007 false   I died.
1008 > ok,res=xpcall(a,debug.traceback)  -- call the function
1009 > print(ok,res)
1010 false   I died.
1011 stack traceback:
1012         [C]: in function 'message'
1013         runme.lua:70: in function 'b'
1014         runme.lua:67: in function &lt;runme.lua:66&gt;
1015         [C]: in function 'xpcall'
1016         runme.lua:95: in main chunk
1017         [C]: ?
1018 </pre></div>
1019
1020 <p>
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>
1022 <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.
1029 </p>
1030 <p>
1031 Therefore by default SWIG converts all thrown object into strings and returns them. So given a function:
1032 </p>
1033
1034 <div class="code"><pre>
1035 void throw_A() throw(A*) {
1036   throw new A();
1037 }
1038 </pre></div>
1039 <p>
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).
1041 </p>
1042
1043 <div class="targetlang"><pre>
1044 > throw_A()
1045 object exception:A *
1046 stack traceback:
1047         [C]: in function 'unknown'
1048         stdin:1: in main chunk
1049         [C]: ?
1050 >
1051 </pre></div>
1052 <p>
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.
1055 </p>
1056 <p>
1057 If you have your own class which you want output as a string you will need to add a typemap something like this:
1058 </p>
1059 <div class="code"><pre>
1060 %typemap(throws) my_except
1061 %{ 
1062   lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
1063   SWIG_fail; // trigger the error handler
1064 %}
1065 </pre></div>
1066 <p>
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:
1069 </p>
1070 <div class="code"><pre>
1071 %apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
1072
1073 class Exc {
1074 public:
1075   Exc(int c, const char *m) {
1076     code = c;
1077     strncpy(msg,m,256);
1078   }
1079   int code;
1080   char msg[256];
1081 };
1082
1083 void throw_exc() throw(Exc) {
1084   throw(Exc(42,"Hosed"));
1085
1086 </pre></div>
1087 <p>
1088 Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
1089 </p>
1090 <div class="targetlang"><pre>
1091 > ok,res=pcall(throw_exc)
1092 > print(ok)
1093 false
1094 > print(res)
1095 userdata: 0003D880
1096 > print(res.code,res.msg)
1097 42      Hosed
1098 >
1099 </pre></div>
1100
1101 <p>
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.
1104 </p>
1105 <p>
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).
1110 </p>
1111
1112
1113 <H2><a name="Lua_nn23"></a>23.4 Typemaps</H2>
1114
1115
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>
1117
1118 <H3><a name="Lua_nn24"></a>23.4.1 What is a typemap?</H3>
1119
1120
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>
1122
1123 <div class="code"><pre>%module example
1124
1125 %typemap(in) int {
1126         $1 = (int) lua_tonumber(L,$input);
1127         printf("Received an integer : %d\n",$1);
1128 }
1129 %inline %{
1130 extern int fact(int n);
1131 %}
1132 </pre></div>
1133
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>
1135
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>
1137
1138 <p>When this example is compiled into a Lua module, it operates as follows:</p>
1139
1140 <div class="targetlang"><pre>&gt; require "example"
1141 &gt; print(example.fact(6))
1142 Received an integer : 6
1143 720
1144 </pre></div>
1145
1146 <H3><a name="Lua_nn25"></a>23.4.2 Using typemaps</H3>
1147
1148
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>
1150
1151 <p>However for more complex functions which use input/output parameters or arrays, you will need to make use of &lt;typemaps.i&gt;, which contains typemaps for these situations. For example, consider these functions:</p>
1152
1153 <div class="code"><pre>void add(int x, int y, int *result) {
1154    *result = x + y;
1155 }
1156
1157 int sub(int *x1, int *y1) {
1158    return *x1-*y1;
1159 }
1160
1161 void swap(int *sx, int *sy) {
1162    int t=*sx;
1163    *sx=*sy;
1164    *sy=t;
1165 }
1166 </pre></div>
1167
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>
1169
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>
1171
1172 <div class="code"><pre>%include &lt;typemaps.i&gt;
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
1176
1177 void add(int x, int y, int *result);
1178 int sub(int *x1, int *y1);
1179 void swap(int *sx, int *sy);
1180 </pre></div>
1181
1182 <p>When wrapped, it gives the following results:</p>
1183
1184 <div class="targetlang"><pre>&gt; require "example"
1185 &gt; print(example.add(1,2))
1186 3
1187 &gt; print(demo.sub(1,2))
1188 -1
1189 &gt; a,b=1,2
1190 &gt; c,d=demo.swap(a,b)
1191 &gt; print(a,b,c,d)
1192 1       2       2       1
1193 </pre></div>
1194
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>
1196
1197 <p>Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a <tt>const int&amp;</tt>  as an input parameter (since that it obviously input).</p>
1198
1199 <H3><a name="Lua_nn26"></a>23.4.3 Typemaps and arrays</H3>
1200
1201
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>
1205
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);
1209 </pre></div>
1210
1211 <p>There are basically two ways that SWIG can deal with this. The first way, uses the <tt>&lt;carrays.i&gt;</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>
1214
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>&lt;typemaps.i&gt;</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>
1216
1217 <p>The wrapper file below, shows both the use of carrays as well as the use of the typemap to wrap arrays. </p>
1218
1219 <div class="code"><pre>// using the C-array
1220 %include &lt;carrays.i&gt;
1221 // this declares a batch of function for manipulating C integer arrays
1222 %array_functions(int,int)
1223
1224 extern void sort_int(int* arr, int len); // the function to wrap
1225
1226 // using typemaps
1227 %include &lt;typemaps.i&gt;
1228 %apply (double *INOUT,int) {(double* arr,int len)};
1229
1230 extern void sort_double(double* arr, int len); // the function to wrap
1231 </pre></div>
1232
1233 <p>Once wrappered, the functions can both be called, though with different ease of use:</p>
1234
1235 <div class="targetlang"><pre>require "example"
1236 ARRAY_SIZE=10
1237
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))
1242 end
1243 example.sort_int(arr,ARRAY_SIZE)  -- call the function
1244 example.delete_int(arr) -- must delete the allocated memory
1245
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
1248 t={} -- a Lua table
1249 for i=1,ARRAY_SIZE do -- index 1..10 (Lua style)
1250     t[i]=math.random(1000)/10
1251 end
1252 t=example.sort_double(t) -- replace t with the result
1253 </pre></div>
1254
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>
1257
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>
1260
1261 <p>Note: SWIG also can support arrays of pointers in a similar manner.</p>
1262
1263 <H3><a name="Lua_nn27"></a>23.4.4 Typemaps and pointer-pointer functions</H3>
1264
1265
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>
1267
1268 <div class="code"><pre>struct iMath;    // some structure
1269 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
1270 </pre></div>
1271
1272 <p>Which would be used with the following C code:</p>
1273
1274 <div class="code"><pre>iMath* ptr;
1275 int ok;
1276 ok=Create_Math(&amp;ptr);
1277 // do things with ptr
1278 //...
1279 free(ptr); // dispose of iMath
1280 </pre></div>
1281
1282 <p>SWIG has a ready written typemap to deal with such a kind of function in &lt;typemaps.i&gt;. 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>
1283
1284 <div class="code"><pre>%include &lt;typemaps.i&gt;
1285 %apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG its an output
1286
1287 struct iMath;    // some structure
1288 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
1289 </pre></div>
1290
1291 <p>The usage is as follows:</p>
1292
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
1295 </pre></div>
1296
1297 <H2><a name="Lua_nn28"></a>23.5 Writing typemaps</H2>
1298
1299
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>
1301
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>
1303
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>
1305
1306 <H3><a name="Lua_nn29"></a>23.5.1 Typemaps you can write</H3>
1307
1308
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>
1310
1311 <ul>
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>
1317 </ul>
1318
1319 <H3><a name="Lua_nn30"></a>23.5.2 SWIG's Lua-C API</H3>
1320
1321
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>
1323
1324 <p><tt>int SWIG_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags);</tt></p>
1325
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()
1330 </div>
1331
1332 <p><tt>void SWIG_NewPointerObj(lua_State* L,void* ptr,swig_type_info *type,int own);</tt></p>
1333
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.
1337 </div>
1338
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>
1340
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.
1343 </div>
1344
1345 <p><tt>SWIG_fail</tt></p>
1346
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");
1352  SWIG_fail;
1353 }</pre></div>
1354
1355 <p><tt>SWIG_fail_arg(char* func_name,int argnum,char* type)</tt></p>
1356
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 
1359 <pre>
1360 "Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'"
1361 </pre></div>
1362
1363 <p><tt>SWIG_fail_ptr(const char* fn_name,int argnum,swig_type_info* type);</tt></p>
1364
1365 <div class="indent">
1366 Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.</div>
1367
1368 <H2><a name="Lua_nn31"></a>23.6 Customization of your Bindings</H2>
1369
1370
1371 <p>
1372 This section covers adding of some small extra bits to your module to add the last finishing touches.
1373 </p>
1374
1375
1376
1377 <H3><a name="Lua_nn32"></a>23.6.1 Writing your own custom wrappers</H3>
1378
1379
1380 <p>
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:
1382 </p>
1383 <div class="code"><pre>%native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
1384 ...
1385 %{
1386 int native_function(lua_State*L) // my native code
1387 {
1388  ...
1389 }
1390 %}
1391 </pre></div>
1392 <p>
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.
1394 </p>
1395
1396 <H3><a name="Lua_nn33"></a>23.6.2 Adding additional Lua code</H3>
1397
1398
1399 <p>
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.
1402 </p>
1403 <p>
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.
1406 </p>
1407 <div class="code"><pre>%module example;
1408
1409 %luacode {
1410   function example.greet() 
1411     print "hello world" 
1412   end
1413
1414   print "Module loaded ok"
1415 }
1416 ...
1417 %}
1418 </pre></div>
1419 <p>
1420 Notice that the code is not part of the module table. Therefore any references to the module must have the 
1421 module name added.
1422 </p>
1423 <p>
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.
1428 </p>
1429 <p>
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.
1432 </p>
1433
1434 <H2><a name="Lua_nn34"></a>23.7 Details on the Lua binding</H2>
1435
1436
1437 <p>
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.
1439 </p>
1440 <p>
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.
1442  </i>
1443 </p>
1444
1445 <H3><a name="Lua_nn35"></a>23.7.1 Binding global data into the module.</H3>
1446
1447
1448 <p>
1449 Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
1450 </p>
1451 <div class="code"><pre>%module example;
1452 extern double Foo;
1453 </pre></div>
1454 <p>
1455 SWIG will effectively generate the pair of functions
1456 </p>
1457 <div class="code"><pre>void Foo_set(double);
1458 double Foo_get();
1459 </pre></div>
1460 <p>
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.
1462 </p>
1463 <div class="targetlang"><pre>
1464 &gt; print(example)
1465 table: 003F8F90
1466 &gt; m=getmetatable(example)
1467 &gt; table.foreach(m,print)
1468 .set    table: 003F9088
1469 .get    table: 003F9038
1470 __index function: 003F8FE0
1471 __newindex      function: 003F8FF8
1472 &gt; g=m['.get']
1473 &gt; table.foreach(g,print)
1474 Foo     function: 003FAFD8
1475 &gt;
1476 </pre></div>
1477 <p>
1478 The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)
1479 </p>
1480 <p>
1481 The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
1482 </p>
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 &amp; returns the value
1489         if type(f)=="function" then return f() end
1490         return nil
1491 end
1492
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
1500 end
1501 </pre></div>
1502 <p>
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)'.
1504 </p>
1505 <H3><a name="Lua_nn36"></a>23.7.2 Userdata and Metatables</H3>
1506
1507
1508 <p>
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.
1510 </p>
1511 <p>
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.
1513 </p>
1514 <p>
1515 Given a class
1516 </p>
1517 <div class="code"><pre>%module excpp;
1518
1519 class Point
1520 {
1521 public:
1522  int x,y;
1523  Point(){x=y=0;}
1524  ~Point(){}
1525  virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
1526 };
1527 </pre></div>
1528 <p>
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.
1530 </p>
1531 <p>
1532 Some of the internals can be seen by looking at a classes metatable.
1533 </p>
1534 <div class="targetlang"><pre>
1535 &gt; p=excpp.Point()
1536 &gt; print(p)
1537 userdata: 003FDB28
1538 &gt; m=getmetatable(p)
1539 &gt; table.foreach(m,print)
1540 .type   Point
1541 __gc    function: 003FB6C8
1542 __newindex      function: 003FB6B0
1543 __index function: 003FB698
1544 .get    table: 003FB4D8
1545 .set    table: 003FB500
1546 .fn     table: 003FB528
1547 </pre></div>
1548 <p>
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)
1550 </p>
1551 <p>
1552 The Lua equivalent of the code for enabling functions looks a little like this
1553 </p>
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 &amp; 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
1570         return nil
1571 end
1572 </pre></div>
1573 <p>
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)'
1575 </p>
1576 <p>
1577 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.
1578 </p>
1579 <p>
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.
1581 </p>
1582 <p>
1583 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.
1584 </p>
1585 <H3><a name="Lua_nn37"></a>23.7.3 Memory management</H3>
1586
1587
1588 <p>
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 &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.
1590 </p>
1591 <p>
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.
1593 </p>
1594 <p>
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)
1596 </p>
1597 </body>
1598 </html>