Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / html / swig / Lua.html
CommitLineData
86530b38
AT
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>29 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</ul>
37<li><a href="#Lua_nn22">Details on the Lua binding</a>
38<ul>
39<li><a href="#Lua_nn23">Binding global data into the module.</a>
40<li><a href="#Lua_nn24">Userdata and Metatables</a>
41<li><a href="#Lua_nn25">Memory management</a>
42</ul>
43</ul>
44</div>
45<!-- INDEX -->
46
47
48
49<p>
50Lua 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>
51</p>
52<H2><a name="Lua_nn2"></a>29.1 Preliminaries</H2>
53
54
55<p>
56The current SWIG implementation is designed to work with Lua 5.0. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms).
57</p>
58<p>
59Note: Lua 5.1 (alpha) has just (as of September 05) been released. The current version of SWIG will produce wrappers which are compatible with Lua 5.1, though the dynamic loading mechanism has changed (see below). The configure script and makefiles should work correctly with with Lua 5.1, though some small tweaks may be needed.
60</p>
61<H2><a name="Lua_nn3"></a>29.2 Running SWIG</H2>
62
63
64<p>
65Suppose that you defined a SWIG module such as the following:
66</p>
67<div class="code"><pre>
68%module example
69%{
70#include "example.h"
71%}
72int gcd(int x, int y);
73extern double Foo;
74</pre></div>
75<p>
76To build a Lua module, run SWIG using the <tt>-lua</tt> option.
77</p>
78<div class="shell"><pre>
79$ swig -lua example.i
80</pre></div>
81<p>
82If building a C++ extension, add the <tt>-c++</tt> option:
83</p>
84<div class="shell"><pre>
85$ swig -c++ -lua example.i
86</pre></div>
87<p>
88This 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.
89</p>
90<p>
91The name of the wrapper file is derived from the name of the input file. For example, if the input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>. To change this, you can use the -o option. The wrappered module will export one function <tt>"int Example_Init(LuaState* L)"</tt> which must be called to register the module with the Lua interpreter. The name "Example_Init" depends upon the name of the module. Note: SWIG will automatically capitalise the module name, so <tt>"module example;"</tt> becomes <tt>"Example_Init"</tt>.
92</p>
93<H3><a name="Lua_nn4"></a>29.2.1 Compiling and Linking and Interpreter</H3>
94
95
96<p>
97Normally Lua is embedded into another program and will be statically linked. An extremely simple stand-alone interpreter (<tt>min.c</tt>) is given below:
98</p>
99<div class="code"><pre>
100#include &lt;stdio.h&gt;
101#include "lua.h"
102#include "lualib.h"
103#include "lauxlib.h"
104
105extern int Example_Init(LuaState* L); // declare the wrapped module
106
107int main(int argc,char* argv[])
108{
109 lua_State *L;
110 if (argc<2)
111 {
112 printf("%s: &lt;filename.lua&gt;\n",argv[0]);
113 return 0;
114 }
115 L=lua_open();
116 luaopen_base(L); // load basic libs (eg. print)
117 Example_Init(L); // load the wrappered module
118 if (luaL_loadfile(L,argv[1])==0) // load and run the file
119 lua_pcall(L,0,0,0);
120 else
121 printf("unable to load %s\n",argv[1]);
122 lua_close(L);
123 return 0;
124}
125</pre></div>
126<p>
127A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",Example_Init}</tt>, at the relevant place.
128</p>
129<p>
130The exact commands for doing this vary from platform to platform. Here is a possible set of commands of doing this:
131</p>
132<div class="shell"><pre>
133$ swig -lua example.i
134$ gcc -I/usr/include/lua -c min.c -o min.o
135$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
136$ gcc -c example.c -o example.o
137$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
138</pre></div>
139
140<H3><a name="Lua_nn5"></a>29.2.2 Compiling a dynamic module</H3>
141
142
143<p>
144Most, 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:
145</p>
146<div class="shell"><pre>
147$ swig -lua example.i
148$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
149$ gcc -c example.c -o example.o
150$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
151</pre></div>
152<p>
153You 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
154</p>
155<div class="targetlang"><pre>
156my_init=loadlib("example.so","Example_Init") -- for Unix/Linux
157--my_init=loadlib("example.dll","Example_Init") -- for Windows
158assert(my_init) -- name sure its not nil
159my_init() -- call the init fn of the lib
160</pre></div>
161<p>
162Or can be done in a single line of Lua code
163</p>
164
165<div class="targetlang"><pre>
166assert(loadlib("example.so","Example_Init"))()
167</pre></div>
168<p>
169Update for Lua 5.1 (alpha):<br>
170The wrappers produced by SWIG can be compiled and linked with Lua 5.1. The loading is now much simpler.
171</p>
172<div class="targetlang"><pre>
173require("example")
174</pre></div>
175
176<H3><a name="Lua_nn6"></a>29.2.3 Using your module</H3>
177
178
179<p>
180Assuming all goes well, you will be able to this:
181</p>
182<div class="targetlang"><pre>
183$ ./my_lua
184&gt; print(example.gcd(4,6))
1852
186&gt; print(example.Foo)
1873
188&gt; example.Foo=4
189&gt; print(example.Foo)
1904
191&gt;
192</pre></div>
193
194<H2><a name="Lua_nn7"></a>29.3 A tour of basic C/C++ wrapping</H2>
195
196
197<p>
198By 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.
199</p>
200<H3><a name="Lua_nn8"></a>29.3.1 Modules</H3>
201
202
203<p>
204The 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.
205</p>
206<H3><a name="Lua_nn9"></a>29.3.2 Functions</H3>
207
208
209<p>
210 Global functions are wrapped as new Lua built-in functions. For example,
211</p>
212<div class="code"><pre>
213%module example
214int fact(int n);</pre></div>
215<p>
216creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
217</p>
218
219<div class="targetlang"><pre>
220&gt; print example.fact(4)
22124
222&gt;
223</pre></div>
224<p>
225To 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.
226</p>
227<div class="targetlang"><pre>
228&gt; for k,v in pairs(example) do _G[k]=v end
229&gt; print(fact(4))
23024
231&gt;
232</pre></div>
233<p>
234It is also possible to rename the module with an assignment.
235</p>
236<div class="targetlang"><pre>
237&gt; e=example
238&gt; print(e.fact(4))
23924
240&gt; print(example.fact(4))
24124
242</pre></div>
243
244<H3><a name="Lua_nn10"></a>29.3.3 Global variables</H3>
245
246
247<p>
248 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:
249</p>
250
251<div class="code"><pre>%module example
252extern double Foo;
253</pre></div>
254<p>
255SWIG will actually generate two functions <tt>example.Foo_set()</tt> and <tt>example.Foo_get()</tt>. It then adds a metatable to the table 'example' to call these functions at the correct time (when you attempt to set or get examples.Foo). Therefore if you were to attempt to assign the global to another variable, you will get a local copy within the interpreter, which is no longer linked to the C code.
256</p>
257
258<div class="targetlang"><pre>
259&gt; print(example.Foo)
2603
261&gt; c=example.Foo -- c is a COPY of example.Foo, not the same thing
262&gt; example.Foo=4
263&gt; print(c)
2643
265&gt; c=5 -- this will not effect the original example.Foo
266&gt; print(example.Foo,c)
2674 5
268</pre></div>
269<p>
270Its 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.
271</p>
272<div class="targetlang"><pre>
273&gt; e=example
274&gt; -- e and example are the same table
275&gt; -- so e.Foo and example.Foo are the same thing
276&gt; example.Foo=4
277&gt; print(e.Foo)
2784
279</pre></div>
280<p>
281If a variable is marked with the immutable directive then any attempts to set this variable are silently ignored.
282</p>
283<p>
284Another interesting feature is that it is not possible to add new values into the module from within the interpreter, this is because of the metatable to deal with global variables. It is possible (though not recommended) to use rawset() to add a new value.
285</p>
286<div class="targetlang"><pre>
287&gt; -- example.PI does not exist
288&gt; print(example.PI)
289nil
290&gt; example.PI=3.142 -- assign failed, example.PI does still not exist
291&gt; print(example.PI)
292nil
293&gt; -- a rawset will work, after this the value is added
294&gt; rawset(example,"PI",3.142)
295&gt; print(example.PI)
2963.142
297</pre></div>
298
299<H3><a name="Lua_nn11"></a>29.3.4 Constants and enums</H3>
300
301
302<p>
303Because 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:
304</p>
305<div class="code"><pre>%module example
306%constant int ICONST=42;
307#define SCONST "Hello World"
308enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
309</pre></div>
310<p>
311This is 'effectively' converted into the following Lua code:
312</p>
313<div class="targetlang"><pre>
314example.ICONST=42
315example.SCONST="Hello World"
316example.SUNDAY=0
317....
318</pre></div>
319<p>
320Constants 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.
321</p>
322<H3><a name="Lua_nn12"></a>29.3.5 Pointers</H3>
323
324
325<p>
326C/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:
327</p>
328<div class="code"><pre>%module example
329
330FILE *fopen(const char *filename, const char *mode);
331int fputs(const char *, FILE *);
332int fclose(FILE *);
333</pre></div>
334<p>
335When wrapped, you will be able to use the functions in a natural way from Lua. For example:
336</p>
337<div class="targetlang"><pre>
338&gt; f=example.fopen("junk","w")
339&gt; example.fputs("Hello World",f)
340&gt; example.fclose(f)
341</pre></div>
342<p>
343Unlike 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).
344</p>
345<div class="targetlang"><pre>
346&gt; print(f)
347userdata: 003FDA80
348&gt; print(swig_type(f))
349_p_FILE -- its a FILE*
350</pre></div>
351<p>
352Lua 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.
353</p>
354<div class="targetlang"><pre>
355&gt; f=example.fopen("not there","r") -- this will return a NULL in C
356&gt; print(f)
357nil
358</pre></div>
359
360<H3><a name="Lua_nn13"></a>29.3.6 Structures</H3>
361
362
363<p>
364 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,
365</p>
366<div class="code"><pre>struct Point{
367 int x,y;
368};
369</pre></div>
370<p>
371is used as follows:
372</p>
373<div class="targetlang"><pre>
374&gt; p=example.Point()
375&gt; p.x=3
376&gt; p.y=5
377&gt; print(p.x,p.y)
3783 5
379&gt;
380</pre></div>
381<p>
382Similar access is provided for unions and the data members of C++ classes.<br>
383SWIG will also create a function <tt>new_Point()</tt> which also creates a new Point structure.
384</p>
385<p>
386If you print out the value of p in the above example, you will see something like this:
387</p>
388<div class="targetlang"><pre>
389&gt; print(p)
390userdata: 003FA320
391</pre></div>
392<p>
393Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG creates some accessor/mutator functions <tt>Point_set_x()</tt> and <tt>Point_get_x()</tt>. These will be wrappered, and then added to the metatable added to the userdata. This provides the natural access to the member variables that were shown above (see end of the document for full details).
394</p>
395<p>
396<tt>const</tt> members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutable's, setting attempts will be silently ignored. For example:
397</p>
398<div class="code"><pre>struct Foo {
399 ...
400 %immutable;
401 int x; // Read-only members
402 char *name;
403 %mutable;
404 ...
405};
406</pre></div>
407<p>
408The 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).
409</p>
410<p>
411When a member of a structure is itself a structure, it is handled as a pointer. For example, suppose you have two structures like this:
412</p>
413
414<div class="code"><pre>struct Foo {
415 int a;
416};
417
418struct Bar {
419 Foo f;
420};
421</pre></div>
422<p>
423Now, suppose that you access the f attribute of Bar like this:
424</p>
425<div class="targetlang"><pre>
426&gt; b = Bar()
427&gt; x = b.f
428</pre></div>
429<p>
430In 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:
431</p>
432<div class="code"><pre>
433Bar b;
434Foo *x = &amp;b-&gt;f; // Points inside b
435</pre></div>
436<p>
437Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
438</p>
439<div class="targetlang"><pre>
440&gt; b = Bar()
441&gt; b.f.a = 3 -- Modify attribute of structure member
442&gt; x = b.f
443&gt; x.a = 3 -- Modifies the same structure
444</pre></div>
445
446<H3><a name="Lua_nn14"></a>29.3.7 C++ classes</H3>
447
448
449<p>
450C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
451</p>
452<div class="code"><pre>class List {
453public:
454 List();
455 ~List();
456 int search(char *item);
457 void insert(char *item);
458 void remove(char *item);
459 char *get(int n);
460 int length;
461};
462</pre></div>
463<p>
464you can use it in Lua like this:
465</p>
466<div class="targetlang"><pre>
467&gt; l = example.List()
468&gt; l.insert("Ale")
469&gt; l.insert("Stout")
470&gt; l.insert("Lager")
471&gt; print(l.get(1))
472Stout
473&gt; print(l.length)
4743
475&gt;
476</pre></div>
477<p>
478Class 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:
479</p>
480<div class="targetlang"><pre>class Spam {
481public:
482 static void foo();
483 static int bar;
484
485};
486</pre></div>
487<p>
488In Lua, the static members can be accessed as follows:
489</p>
490<div class="code"><pre>
491&gt; example.Spam_foo() -- Spam::foo() the only way currently
492&gt; a=example.Spam_bar_get() -- Spam::bar the hard way
493&gt; a=example.Spam_bar -- Spam::bar the nicer way
494&gt; example.Spam_bar_set(b) -- Spam::bar the hard way
495&gt; example.Spam_bar=b -- Spam::bar the nicer way
496</pre></div>
497<p>
498It is not (currently) possible to access static members of an instance:
499</p>
500<div class="targetlang"><pre>
501&gt; s=example.Spam() -- s is a Spam instance
502&gt; s.foo() -- Spam::foo() via an instance
503 -- does NOT work
504</pre></div>
505
506<H3><a name="Lua_nn15"></a>29.3.8 C++ inheritance</H3>
507
508
509<p>
510SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
511</p>
512<div class="code"><pre>class Foo {
513...
514};
515
516class Bar : public Foo {
517...
518};
519</pre></div>
520<p>
521And if you have functions like this
522</p>
523<div class="code"><pre>void spam(Foo *f);
524</pre></div>
525<p>
526then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
527</p>
528<p>
529It is safe to use multiple inheritance with SWIG.
530</p>
531<H3><a name="Lua_nn16"></a>29.3.9 Pointers, references, values, and arrays</H3>
532
533
534<p>
535In C++, there are many different ways a function might receive and manipulate objects. For example:
536</p>
537<div class="code"><pre>void spam1(Foo *x); // Pass by pointer
538void spam2(Foo &amp;x); // Pass by reference
539void spam3(Foo x); // Pass by value
540void spam4(Foo x[]); // Array of objects
541</pre></div>
542<p>
543In 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:
544</p>
545<div class="targetlang"><pre>
546&gt; f = Foo() -- Create a Foo
547&gt; spam1(f) -- Ok. Pointer
548&gt; spam2(f) -- Ok. Reference
549&gt; spam3(f) -- Ok. Value.
550&gt; spam4(f) -- Ok. Array (1 element)
551</pre></div>
552<p>
553Similar behaviour occurs for return values. For example, if you had functions like this,
554</p>
555<div class="code"><pre>Foo *spam5();
556Foo &amp;spam6();
557Foo spam7();
558</pre></div>
559<p>
560then 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.
561</p>
562<H3><a name="Lua_nn17"></a>29.3.10 C++ overloaded functions</H3>
563
564
565<p>
566C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
567</p>
568<div class="code"><pre>void foo(int);
569void foo(char *c);
570</pre></div>
571<p>
572You can use them in Lua in a straightforward manner:
573</p>
574<div class="targetlang"><pre>
575&gt; foo(3) -- foo(int)
576&gt; foo("Hello") -- foo(char *c)
577</pre></div>
578<p>
579However due to Lua's coercion mechanism is can sometimes do strange things.
580</p>
581<div class="targetlang"><pre>
582&gt; foo("3") -- "3" can be coerced into an int, so it calls foo(int)!
583</pre></div>
584<p>
585As 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).
586</p>
587<p>
588Similarly, if you have a class like this,
589</p>
590<div class="code"><pre>class Foo {
591public:
592 Foo();
593 Foo(const Foo &amp;);
594 ...
595};
596</pre></div>
597<p>
598you can write Lua code like this:
599</p>
600<div class="targetlang"><pre>
601&gt; f = Foo() -- Create a Foo
602&gt; g = Foo(f) -- Copy f
603</pre></div>
604<p>
605Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
606</p>
607<div class="code"><pre>void spam(int);
608void spam(short);
609</pre></div>
610<p>
611or
612</p>
613<DIV CLASS="CODE"><PRE>VOID FOO(bAR *B);
614void foo(Bar &amp;b);
615</pre></div>
616<p>
617If declarations such as these appear, you will get a warning message like this:
618</p>
619<div class="shell"><pre>
620example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
621at example.i:11.
622</pre></div>
623<p>
624 To fix this, you either need to ignore or rename one of the methods. For example:
625</p>
626<div class="code"><pre>%rename(spam_short) spam(short);
627...
628void spam(int);
629void spam(short); // Accessed as spam_short
630</pre></div>
631<p>
632or
633</p>
634<div class="code"><pre>%ignore spam(short);
635...
636void spam(int);
637void spam(short); // Ignored
638</pre></div>
639<p>
640SWIG 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.
641</p>
642<p>
643Please refer to the "SWIG and C++" chapter for more information about overloading.
644</p>
645<p>
646Dealing 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.
647</p>
648<H3><a name="Lua_nn18"></a>29.3.11 C++ operators</H3>
649
650
651<p>
652Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
653</p>
654<div class="code"><pre>class Complex {
655private:
656 double rpart, ipart;
657public:
658 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
659 Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
660 Complex &amp;operator=(const Complex &amp;c);
661 Complex operator+(const Complex &amp;c) const;
662 Complex operator-(const Complex &amp;c) const;
663 Complex operator*(const Complex &amp;c) const;
664 Complex operator-() const;
665
666 double re() const { return rpart; }
667 double im() const { return ipart; }
668};
669</pre></div>
670<p>
671When wrapped, it works like you expect:
672</p>
673<div class="targetlang"><pre>
674&gt; c = Complex(3,4)
675&gt; d = Complex(7,8)
676&gt; e = c + d
677&gt; e:re()
67810.0
679&gt; e:im()
68012.0
681</pre></div>
682<p>
683(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.)
684</p>
685<p>
686One 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
687</p>
688<div class="targetlang"><pre>class Complex {
689...
690friend Complex operator+(double, const Complex &amp;c);
691...
692};
693</pre></div>
694<p>
695then 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:
696</p>
697<div class="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &amp;);
698...
699Complex operator+(double, const Complex &amp;c);
700</pre></div>
701<p>
702There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
703</p>
704<p>
705Also, 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>).
706</p>
707<p>
708In 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).
709<p>
710The current list of operators which can be overloaded (and the alternative function names) are:<ul>
711<li><tt>__add__</tt> operator+
712<li><tt>__sub__</tt> operator-
713<li><tt>__mul__</tt> operator *
714<li><tt>__div__</tt> operator/
715<li><tt>__neg__</tt> unary minus
716<li><tt>__call__</tt> operator<tt>()</tt> (often used in functor classes)
717<li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>^</tt>)
718<li><tt>__concat__</tt> the concatenation operator (SWIG maps C++'s <tt>~</tt> to Lua's <tt>..</tt>)
719<li><tt>__eq__</tt> operator<tt>==</tt>
720<li><tt>__lt__</tt> operator<tt>&lt;</tt>
721<li><tt>__le__</tt> operator<tt>&lt;=</tt>
722</ul>
723<p>
724Note: 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.
725</p>
726<p>
727The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
728<li>++ and --<li>+=,-=,*= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
729<p>
730SWIG 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
731</p>
732<div class="code"><pre>const char* __str__()
733{
734 static char buffer[255];
735 sprintf(buffer,"Complex(%g,%g)",this-&gt;re(),this-&gt;im());
736 return buffer;
737}
738</pre></div>
739<p>
740Then this will support the following code in Lua
741</p>
742<div class="targetlang"><pre>
743&gt; c = Complex(3,4)
744&gt; d = Complex(7,8)
745&gt; e = c + d
746&gt; print(e)
747Complex(10,12)
748&gt; s=tostring(e) -- s is the number in string form
749&gt; print(s)
750Complex(10,12)
751</pre></div>
752<p>
753It 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>
754</p>
755<div class="code"><pre>class Complex
756{
757 //....
758 double __getitem__(int i)const; // i is the index, returns the data
759 void __setitem__(int i,double d); // i is the index, d is the data
760};
761</pre></div>
762
763<H3><a name="Lua_nn19"></a>29.3.12 Class extension with %extend</H3>
764
765
766<p>
767 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.
768</p>
769<p>
770Take the original Complex class
771</p>
772<div class="code"><pre>class Complex {
773private:
774 double rpart, ipart;
775public:
776 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
777 Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
778 Complex &amp;operator=(const Complex &amp;c);
779 Complex operator+(const Complex &amp;c) const;
780 Complex operator-(const Complex &amp;c) const;
781 Complex operator*(const Complex &amp;c) const;
782 Complex operator-() const;
783
784 double re() const { return rpart; }
785 double im() const { return ipart; }
786};
787</pre></div>
788<p>
789Now we extend it with some new code
790</p>
791<div class="code"><pre>%extend Complex {
792 const char *__str__() {
793 static char tmp[1024];
794 sprintf(tmp,"Complex(%g,%g)", self-&gt;re(),self-&gt;im());
795 return tmp;
796 }
797 bool operator==(const Complex&amp; c)
798 { return (self-&gt;re()==c.re() &amp;&amp; self-&gt;im()==c.im();}
799};
800</pre></div>
801<p>
802Now, in Lua
803</p>
804<div class="targetlang"><pre>
805&gt; c = Complex(3,4)
806&gt; d = Complex(7,8)
807&gt; e = c + d
808&gt; print(e) -- print uses __str__ to get the string form to print
809Complex(10,12)
810&gt; print(e==Complex(10,12)) -- testing the == operator
811true
812&gt; print(e!=Complex(12,12)) -- the != uses the == operator
813true
814</pre></div>
815<p>
816Extend 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).
817</p>
818<H3><a name="Lua_nn20"></a>29.3.13 C++ templates</H3>
819
820
821<p>
822 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:
823</p>
824<div class="code"><pre>%module example
825%{
826#include "pair.h"
827%}
828
829template&lt;class T1, class T2&gt;
830struct pair {
831 typedef T1 first_type;
832 typedef T2 second_type;
833 T1 first;
834 T2 second;
835 pair();
836 pair(const T1&amp;, const T2&amp;);
837 ~pair();
838};
839
840%template(pairii) pair&lt;int,int&gt;;
841</pre></div>
842<p>
843In Lua:
844</p>
845<div class="targetlang"><pre>
846&gt; p = example.pairii(3,4)
847&gt; print(p.first,p.second)
8483 4
849</pre></div>
850<p>
851Obviously, 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.
852</p>
853<H3><a name="Lua_nn21"></a>29.3.14 C++ Smart Pointers</H3>
854
855
856<p>
857 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:
858</p>
859<div class="code"><pre>template&lt;class T&gt; class SmartPtr {
860 ...
861 T *operator-&gt;();
862 ...
863}
864</pre></div>
865<p>
866Then, if you have a class like this,
867</p>
868<div class="code"><pre>class Foo {
869public:
870 int x;
871 int bar();
872};
873</pre></div>
874<p>
875A smart pointer would be used in C++ as follows:
876</p>
877<div class="code"><pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
878...
879p-&gt;x = 3; // Foo::x
880int y = p-&gt;bar(); // Foo::bar
881</pre></div>
882<p>
883To 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:
884</p>
885<div class="code"><pre>%module example
886...
887%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
888...
889</pre></div>
890<p>
891Now, in Lua, everything should just "work":
892</p>
893<div class="targetlang"><pre>
894&gt; p = example.CreateFoo() -- Create a smart-pointer somehow
895&gt; p.x = 3 -- Foo::x
896&gt; print(p:bar()) -- Foo::bar
897</pre></div>
898<p>
899If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt> method. For example:
900</p>
901<div class="targetlang"><pre>
902&gt; f = p:__deref__() -- Returns underlying Foo *
903</pre></div>
904
905<H2><a name="Lua_nn22"></a>29.4 Details on the Lua binding</H2>
906
907
908<p>
909 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.
910</p>
911<p>
912 <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.
913 </i>
914</p>
915
916<H3><a name="Lua_nn23"></a>29.4.1 Binding global data into the module.</H3>
917
918
919<p>
920Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
921</p>
922<div class="code"><pre>%module example;
923extern double Foo;
924</pre></div>
925<p>
926SWIG will effectively generate the pair of functions
927</p>
928<div class="code"><pre>void Foo_set(double);
929double Foo_get();
930</pre></div>
931<p>
932At initialisation time, it will then add to the interpreter a table called 'example', which represents the module. It will then add all its functions to the module. But it also adds a metatable to this table, which has two functions (<tt>__index</tt> and <tt>__newindex</tt>) as well as two tables (<tt>.get</tt> and <tt>.set</tt>) The following Lua code will show these hidden features.
933</p>
934<div class="targetlang"><pre>
935&gt; print(example)
936table: 003F8F90
937&gt; m=getmetatable(example)
938&gt; table.foreach(m,print)
939.set table: 003F9088
940.get table: 003F9038
941__index function: 003F8FE0
942__newindex function: 003F8FF8
943&gt; g=m['.get']
944&gt; table.foreach(g,print)
945Foo function: 003FAFD8
946&gt;
947</pre></div>
948<p>
949The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)
950</p>
951<p>
952The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
953</p>
954<div class="targetlang"><pre>
955function __index(mod,name)
956 local g=getmetatable(mod)['.get'] -- gets the table
957 if not g then return nil end
958 local f=g[name] -- looks for the function
959 -- calls it &amp; returns the value
960 if type(f)=="function" then return f() end
961 return nil
962end
963
964function __newindex(mod,name,value)
965 local s=getmetatable(mod)['.set'] -- gets the table
966 if not s then return end
967 local f=s[name] -- looks for the function
968 -- calls it to set the value
969 if type(f)=="function" then f(value) end
970end
971</pre></div>
972<p>
973That 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)'.
974</p>
975<H3><a name="Lua_nn24"></a>29.4.2 Userdata and Metatables</H3>
976
977
978<p>
979As 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.
980</p>
981<p>
982The 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.
983</p>
984<p>
985Given a class
986</p>
987<div class="code"><pre>%module excpp;
988
989class Point
990{
991public:
992 int x,y;
993 Point(){x=y=0;}
994 ~Point(){}
995 virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
996};
997</pre></div>
998<p>
999SWIG 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.
1000</p>
1001<p>
1002Some of the internals can be seen by looking at a classes metatable.
1003</p>
1004<div class="targetlang"><pre>
1005&gt; p=excpp.Point()
1006&gt; print(p)
1007userdata: 003FDB28
1008&gt; m=getmetatable(p)
1009&gt; table.foreach(m,print)
1010.type Point
1011__gc function: 003FB6C8
1012__newindex function: 003FB6B0
1013__index function: 003FB698
1014.get table: 003FB4D8
1015.set table: 003FB500
1016.fn table: 003FB528
1017</pre></div>
1018<p>
1019The '.type' attribute is the string which is returned from a call to swig_type(). The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the classes destructor function)
1020</p>
1021<p>
1022The Lua equivalent of the code for enabling functions looks a little like this
1023</p>
1024<div class="targetlang"><pre>
1025function __index(obj,name)
1026 local m=getmetatable(obj) -- gets the metatable
1027 if not m then return nil end
1028 local g=m['.get'] -- gets the attribute table
1029 if not g then return nil end
1030 local f=g[name] -- looks for the get_attribute function
1031 -- calls it &amp; returns the value
1032 if type(f)=="function" then return f() end
1033 -- ok, so it not an attribute, maybe its a function
1034 local fn=m['.fn'] -- gets the function table
1035 if not fn then return nil end
1036 local f=fn[name] -- looks for the function
1037 -- if found the fn then return the function
1038 -- so the interpreter can call it
1039 if type(f)=="function" then return f end
1040 return nil
1041end
1042</pre></div>
1043<p>
1044So 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)'
1045</p>
1046<p>
1047In 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.
1048</p>
1049<p>
1050Note: 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.
1051</p>
1052<p>
1053Note: 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.
1054</p>
1055<H3><a name="Lua_nn25"></a>29.4.3 Memory management</H3>
1056
1057
1058<p>
1059Lua 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.
1060</p>
1061<p>
1062It 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.
1063</p>
1064<p>
1065It 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)
1066</p>
1067</body>
1068</html>