~ubuntu-branches/ubuntu/oneiric/swig1.3/oneiric

« back to all changes in this revision

Viewing changes to Doc/Manual/Lua.html

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-12-06 10:27:08 UTC
  • mfrom: (1.2.6 upstream)
  • Revision ID: james.westby@ubuntu.com-20071206102708-t37t62i45n595w0e
Tags: 1.3.33-2ubuntu1
* Merge with Debian; remaining changes:
  - Drop support for pike.
  - Use python2.5 instead of python2.4.
  - Clean Runtime/ as well.
  - Force a few environment variables.
* debian/Rules (clean): Remove Lib/ocaml/swigp4.ml.

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
<li><a href="#Lua_nn19">Class extension with %extend</a>
34
34
<li><a href="#Lua_nn20">C++ templates</a>
35
35
<li><a href="#Lua_nn21">C++ Smart Pointers</a>
 
36
<li><a href="#Lua_nn22">Writing your own custom wrappers</a>
36
37
</ul>
37
 
<li><a href="#Lua_nn22">Details on the Lua binding</a>
 
38
<li><a href="#Lua_nn23">Details on the Lua binding</a>
38
39
<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>
 
40
<li><a href="#Lua_nn24">Binding global data into the module.</a>
 
41
<li><a href="#Lua_nn25">Userdata and Metatables</a>
 
42
<li><a href="#Lua_nn26">Memory management</a>
42
43
</ul>
43
44
</ul>
44
45
</div>
53
54
 
54
55
 
55
56
<p>
56
 
The current SWIG implementation is designed to work with Lua 5.0. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms).
57
 
</p>
58
 
<p>
59
 
Note: Lua 5.1 (alpha) has just (as of September 05) been released. The current version of SWIG will produce wrappers which are compatible with Lua 5.1, though the  dynamic loading mechanism has changed (see below). The configure script and makefiles should work correctly with with Lua 5.1, though some small tweaks may be needed.
 
57
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).
60
58
</p>
61
59
<H2><a name="Lua_nn3"></a>22.2 Running SWIG</H2>
62
60
 
88
86
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.
89
87
</p>
90
88
<p>
91
 
The name of the wrapper file is derived from the name of the input file. For example, if the input file is <tt>example.i</tt>, the name of the wrapper file is <tt>example_wrap.c</tt>. To change this, you can use the -o option. The wrappered module will export one function <tt>"int Example_Init(LuaState* L)"</tt> which must be called to register the module with the Lua interpreter. The name "Example_Init" depends upon the name of the module. Note: SWIG will automatically capitalise the module name, so <tt>"module example;"</tt> becomes <tt>"Example_Init"</tt>.
 
89
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(LuaState* 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.
92
90
</p>
93
91
<H3><a name="Lua_nn4"></a>22.2.1 Compiling and Linking and Interpreter</H3>
94
92
 
102
100
#include "lualib.h"
103
101
#include "lauxlib.h"
104
102
 
105
 
extern int Example_Init(LuaState* L); // declare the wrapped module
 
103
extern int luaopen_example(LuaState* L); // declare the wrapped module
106
104
 
107
105
int main(int argc,char* argv[])
108
106
{
109
107
 lua_State *L;
110
 
 if (argc<2)
 
108
 if (argc&lt;2)
111
109
 {
112
110
  printf("%s: &lt;filename.lua&gt;\n",argv[0]);
113
111
  return 0;
114
112
 }
115
113
 L=lua_open();
116
114
 luaopen_base(L);       // load basic libs (eg. print)
117
 
 Example_Init(L);       // load the wrappered module
 
115
 luaopen_example(L);    // load the wrappered module
118
116
 if (luaL_loadfile(L,argv[1])==0) // load and run the file
119
117
  lua_pcall(L,0,0,0);
120
118
 else
124
122
}
125
123
</pre></div>
126
124
<p>
127
 
A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",Example_Init}</tt>, at the relevant place.
 
125
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.
128
126
</p>
129
127
<p>
130
128
The exact commands for doing this vary from platform to platform. Here is a possible set of commands of doing this:
150
148
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
151
149
</pre></div>
152
150
<p>
153
 
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
154
 
</p>
155
 
<div class="targetlang"><pre>
156
 
my_init=loadlib("example.so","Example_Init") -- for Unix/Linux
157
 
--my_init=loadlib("example.dll","Example_Init") -- for Windows
 
151
The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x. The loading is extremely simple.
 
152
</p>
 
153
<div class="targetlang"><pre>
 
154
require("example")
 
155
</pre></div>
 
156
<p>
 
157
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
 
158
</p>
 
159
<div class="targetlang"><pre>
 
160
my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux
 
161
--my_init=loadlib("example.dll","luaopen_example") -- for Windows
158
162
assert(my_init) -- name sure its not nil
159
163
my_init()       -- call the init fn of the lib
160
164
</pre></div>
161
165
<p>
162
166
Or can be done in a single line of Lua code
163
167
</p>
 
168
<div class="targetlang"><pre>
 
169
assert(loadlib("example.so","luaopen_example"))()
 
170
</pre></div>
164
171
 
165
 
<div class="targetlang"><pre>
166
 
assert(loadlib("example.so","Example_Init"))()
167
 
</pre></div>
168
 
<p>
169
 
Update for Lua 5.1 (alpha):<br>
170
 
The 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>
173
 
require("example")
174
 
</pre></div>
175
172
 
176
173
<p>
177
174
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).
178
175
</p>
179
176
<div class="targetlang"><pre>
180
 
a,b,c=loadlib("example.so","Example_Init") -- for Unix/Linux
181
 
--a,b,c=loadlib("example.dll","Example_Init") -- for Windows
 
177
a,b,c=package.loadlib("example.so","luaopen_example") -- for Unix/Linux
 
178
--a,b,c=package.loadlib("example.dll","luaopen_example") -- for Windows
182
179
print(a,b,c)
183
180
</pre></div>
184
181
<p>
185
 
Note: for Lua 5.1:<br>
186
 
The loadlib() function has been moved into the package table, so you must use package.loadlib() instead.
 
182
Note: for Lua 5.0:<br>
 
183
The loadlib() function is in the global namespace, not in package. So its just loadlib().
187
184
</p>
188
185
<p>
189
186
if 'a' is a function, this its all working fine, all you need to do is call it
285
282
extern double Foo;
286
283
</pre></div>
287
284
<p>
288
 
SWIG will actually generate two functions <tt>example.Foo_set()</tt> and <tt>example.Foo_get()</tt>. It then adds a metatable to the table 'example' to call these functions at the correct time (when you attempt to set or get examples.Foo). Therefore if you were to attempt to assign the global to another variable, you will get a local copy within the interpreter, which is no longer linked to the C code.
 
285
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.
289
286
</p>
290
287
 
291
288
<div class="targetlang"><pre>
311
308
4
312
309
</pre></div>
313
310
<p>
314
 
If a variable is marked with the immutable directive then any attempts to set this variable are silently ignored.
315
 
</p>
316
 
<p>
317
 
Another interesting feature is that it is not possible to add new values into the module from within the interpreter, this is because of the metatable to deal with global variables. It is possible (though not recommended) to use rawset() to add a new value.
 
311
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:
 
312
</p>
 
313
 
 
314
<div class="code"><pre>%module example
 
315
%immutable;
 
316
extern double Foo;
 
317
%mutable;
 
318
</pre></div>
 
319
<p>
 
320
SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
 
321
</p>
 
322
<div class="targetlang"><pre>
 
323
&gt; print(e.Foo) -- reading works ok
 
324
4
 
325
&gt; example.Foo=40 -- but writing does not
 
326
This variable is immutable
 
327
stack traceback:
 
328
        [C]: ?
 
329
        [C]: ?
 
330
        stdin:1: in main chunk
 
331
        [C]: ?
 
332
</pre></div>
 
333
<p>
 
334
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.
 
335
</p>
 
336
<p>
 
337
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.
318
338
</p>
319
339
<div class="targetlang"><pre>
320
340
&gt; -- example.PI does not exist
321
341
&gt; print(example.PI)
322
342
nil
323
 
&gt; example.PI=3.142 -- assign failed, example.PI does still not exist
324
 
&gt; print(example.PI)
325
 
nil
326
 
&gt; -- a rawset will work, after this the value is added
327
 
&gt; rawset(example,"PI",3.142)
 
343
&gt; example.PI=3.142 -- new value added
328
344
&gt; print(example.PI)
329
345
3.142
330
346
</pre></div>
379
395
&gt; print(f)
380
396
userdata: 003FDA80
381
397
&gt; print(swig_type(f))
382
 
_p_FILE -- its a FILE*
 
398
FILE * -- its a FILE*
383
399
</pre></div>
384
400
<p>
385
401
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.
404
420
is used as follows:
405
421
</p>
406
422
<div class="targetlang"><pre>
407
 
&gt; p=example.Point()
 
423
&gt; p=example.new_Point()
408
424
&gt; p.x=3
409
425
&gt; p.y=5
410
426
&gt; print(p.x,p.y)
413
429
</pre></div>
414
430
<p>
415
431
Similar access is provided for unions and the data members of C++ classes.<br>
416
 
SWIG will also create a function <tt>new_Point()</tt> which also creates a new Point structure.
 
432
C structures are created using a function <tt>new_Point()</tt>, but for C++ classes are created using just the name <tt>Point()</tt>.
417
433
</p>
418
434
<p>
419
435
If you print out the value of p in the above example, you will see something like this:
423
439
userdata: 003FA320
424
440
</pre></div>
425
441
<p>
426
 
Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG creates some accessor/mutator functions <tt>Point_set_x()</tt> and <tt>Point_get_x()</tt>. These will be wrappered, and then added to the metatable added to the userdata. This provides the natural access to the member variables that were shown above (see end of the document for full details).
 
442
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).
427
443
</p>
428
444
<p>
429
 
<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:
 
445
<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:
430
446
</p>
431
447
<div class="code"><pre>struct Foo {
432
448
   ...
524
540
In Lua, the static members can be accessed as follows:
525
541
</p>
526
542
<div class="code"><pre>
527
 
&gt; example.Spam_foo()            -- Spam::foo() the only way currently
528
 
&gt; a=example.Spam_bar_get()      -- Spam::bar the hard way
529
 
&gt; a=example.Spam_bar            -- Spam::bar the nicer way
530
 
&gt; example.Spam_bar_set(b)       -- Spam::bar the hard way
531
 
&gt; example.Spam_bar=b            -- Spam::bar the nicer way
 
543
&gt; example.Spam_foo()            -- calling Spam::foo()
 
544
&gt; a=example.Spam_bar            -- reading Spam::bar 
 
545
&gt; example.Spam_bar=b            -- writing to Spam::bar
532
546
</pre></div>
533
547
<p>
534
548
It is not (currently) possible to access static members of an instance:
935
949
&gt; f = p:__deref__()     -- Returns underlying Foo *
936
950
</pre></div>
937
951
 
938
 
<H2><a name="Lua_nn22"></a>22.4 Details on the Lua binding</H2>
 
952
<H3><a name="Lua_nn22"></a>22.3.15 Writing your own custom wrappers</H3>
 
953
 
 
954
 
 
955
<p>
 
956
Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native lua-c 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:
 
957
</p>
 
958
<div class="code"><pre>%native(my_func) int native_function(lua_State*L);  // registers it with SWIG
 
959
...
 
960
%{
 
961
int native_function(lua_State*L) // my native code
 
962
{
 
963
 ...
 
964
}
 
965
%}
 
966
</pre></div>
 
967
<p>
 
968
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.
 
969
</p>
 
970
 
 
971
<H2><a name="Lua_nn23"></a>22.4 Details on the Lua binding</H2>
939
972
 
940
973
 
941
974
<p>
946
979
 </i>
947
980
</p>
948
981
 
949
 
<H3><a name="Lua_nn23"></a>22.4.1 Binding global data into the module.</H3>
 
982
<H3><a name="Lua_nn24"></a>22.4.1 Binding global data into the module.</H3>
950
983
 
951
984
 
952
985
<p>
962
995
double Foo_get();
963
996
</pre></div>
964
997
<p>
965
 
At initialisation time, it will then add to the interpreter a table called 'example', which represents the module. It will then add all its functions to the module. But it also adds a metatable to this table, which has two functions (<tt>__index</tt> and <tt>__newindex</tt>) as well as two tables (<tt>.get</tt> and <tt>.set</tt>) The following Lua code will show these hidden features.
 
998
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 and 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.
966
999
</p>
967
1000
<div class="targetlang"><pre>
968
1001
&gt; print(example)
999
1032
        if not s then return end
1000
1033
        local f=s[name] -- looks for the function
1001
1034
        -- calls it to set the value
1002
 
        if type(f)=="function" then f(value) end
 
1035
        if type(f)=="function" then f(value)
 
1036
        else rawset(mod,name,value) end
1003
1037
end
1004
1038
</pre></div>
1005
1039
<p>
1006
1040
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)'.
1007
1041
</p>
1008
 
<H3><a name="Lua_nn24"></a>22.4.2 Userdata and Metatables</H3>
 
1042
<H3><a name="Lua_nn25"></a>22.4.2 Userdata and Metatables</H3>
1009
1043
 
1010
1044
 
1011
1045
<p>
1049
1083
.fn     table: 003FB528
1050
1084
</pre></div>
1051
1085
<p>
1052
 
The '.type' attribute is the string which is returned from a call to swig_type(). The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the classes destructor function)
 
1086
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)
1053
1087
</p>
1054
1088
<p>
1055
1089
The Lua equivalent of the code for enabling functions looks a little like this
1085
1119
<p>
1086
1120
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.
1087
1121
</p>
1088
 
<H3><a name="Lua_nn25"></a>22.4.3 Memory management</H3>
 
1122
<H3><a name="Lua_nn26"></a>22.4.3 Memory management</H3>
1089
1123
 
1090
1124
 
1091
1125
<p>