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>
37
<li><a href="#Lua_nn22">Details on the Lua binding</a>
38
<li><a href="#Lua_nn23">Details on the Lua binding</a>
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>
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).
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).
61
59
<H2><a name="Lua_nn3"></a>22.2 Running SWIG</H2>
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.
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.
93
91
<H3><a name="Lua_nn4"></a>22.2.1 Compiling and Linking and Interpreter</H3>
102
100
#include "lualib.h"
103
101
#include "lauxlib.h"
105
extern int Example_Init(LuaState* L); // declare the wrapped module
103
extern int luaopen_example(LuaState* L); // declare the wrapped module
107
105
int main(int argc,char* argv[])
112
110
printf("%s: <filename.lua>\n",argv[0]);
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);
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 & 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 & add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place.
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
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
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.
153
<div class="targetlang"><pre>
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
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
162
166
Or can be done in a single line of Lua code
168
<div class="targetlang"><pre>
169
assert(loadlib("example.so","luaopen_example"))()
165
<div class="targetlang"><pre>
166
assert(loadlib("example.so","Example_Init"))()
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.
172
<div class="targetlang"><pre>
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).
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
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().
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;
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.
291
288
<div class="targetlang"><pre>
314
If a variable is marked with the immutable directive then any attempts to set this variable are silently ignored.
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:
314
<div class="code"><pre>%module example
320
SWIG will allow the the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
322
<div class="targetlang"><pre>
323
> print(e.Foo) -- reading works ok
325
> example.Foo=40 -- but writing does not
326
This variable is immutable
330
stdin:1: in main chunk
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.
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.
319
339
<div class="targetlang"><pre>
320
340
> -- example.PI does not exist
321
341
> print(example.PI)
323
> example.PI=3.142 -- assign failed, example.PI does still not exist
324
> print(example.PI)
326
> -- a rawset will work, after this the value is added
327
> rawset(example,"PI",3.142)
343
> example.PI=3.142 -- new value added
328
344
> print(example.PI)
423
439
userdata: 003FA320
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).
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:
431
447
<div class="code"><pre>struct Foo {
524
540
In Lua, the static members can be accessed as follows:
526
542
<div class="code"><pre>
527
> example.Spam_foo() -- Spam::foo() the only way currently
528
> a=example.Spam_bar_get() -- Spam::bar the hard way
529
> a=example.Spam_bar -- Spam::bar the nicer way
530
> example.Spam_bar_set(b) -- Spam::bar the hard way
531
> example.Spam_bar=b -- Spam::bar the nicer way
543
> example.Spam_foo() -- calling Spam::foo()
544
> a=example.Spam_bar -- reading Spam::bar
545
> example.Spam_bar=b -- writing to Spam::bar
534
548
It is not (currently) possible to access static members of an instance:
935
949
> f = p:__deref__() -- Returns underlying Foo *
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>
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:
958
<div class="code"><pre>%native(my_func) int native_function(lua_State*L); // registers it with SWIG
961
int native_function(lua_State*L) // my native code
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.
971
<H2><a name="Lua_nn23"></a>22.4 Details on the Lua binding</H2>
962
995
double Foo_get();
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.
967
1000
<div class="targetlang"><pre>
968
1001
> 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
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)'.
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>