blob: 431ac1c14563eaaa413854c2b06d0ba4c0f2a9b6 [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SWIG and Lua</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Lua">28 SWIG and Lua</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Lua_nn2">Preliminaries</a>
<li><a href="#Lua_nn3">Running SWIG</a>
<ul>
<li><a href="#Lua_commandline">Additional command line options</a>
<li><a href="#Lua_nn4">Compiling and Linking and Interpreter</a>
<li><a href="#Lua_nn5">Compiling a dynamic module</a>
<li><a href="#Lua_nn6">Using your module</a>
</ul>
<li><a href="#Lua_nn7">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="#Lua_nn8">Modules</a>
<li><a href="#Lua_nn9">Functions</a>
<li><a href="#Lua_nn10">Global variables</a>
<li><a href="#Lua_nn11">Constants and enums</a>
<ul>
<li><a href="#Lua_nn13">Constants/enums and classes/structures</a>
</ul>
<li><a href="#Lua_nn12">Pointers</a>
<li><a href="#Lua_structures">Structures</a>
<li><a href="#Lua_nn14">C++ classes</a>
<li><a href="#Lua_nn15">C++ inheritance</a>
<li><a href="#Lua_nn16">Pointers, references, values, and arrays</a>
<li><a href="#Lua_nn17">C++ overloaded functions</a>
<li><a href="#Lua_nn18">C++ operators</a>
<li><a href="#Lua_nn19">Class extension with %extend</a>
<li><a href="#Lua_nn20">Using %newobject to release memory</a>
<li><a href="#Lua_nn21">C++ templates</a>
<li><a href="#Lua_nn22">C++ Smart Pointers</a>
<li><a href="#Lua_nn23">C++ Exceptions</a>
<li><a href="#Lua_namespaces">Namespaces </a>
<ul>
<li><a href="#Lua_nn27">Compatibility Note </a>
<li><a href="#Lua_nn29">Names </a>
<li><a href="#Lua_nn30">Inheritance </a>
</ul>
</ul>
<li><a href="#Lua_nn24">Typemaps</a>
<ul>
<li><a href="#Lua_nn25">What is a typemap?</a>
<li><a href="#Lua_nn26">Using typemaps</a>
<li><a href="#Lua_typemap_arrays">Typemaps and arrays</a>
<li><a href="#Lua_typemaps_ptr_ptr_functions">Typemaps and pointer-pointer functions</a>
</ul>
<li><a href="#Lua_writing_typemaps">Writing typemaps</a>
<ul>
<li><a href="#Lua_typemaps_write">Typemaps you can write</a>
<li><a href="#Lua_nn31">SWIG's Lua-C API</a>
</ul>
<li><a href="#Lua_nn32">Customization of your Bindings</a>
<ul>
<li><a href="#Lua_nn33">Writing your own custom wrappers</a>
<li><a href="#Lua_nn34">Adding additional Lua code</a>
</ul>
<li><a href="#Lua_nn35">Details on the Lua binding</a>
<ul>
<li><a href="#Lua_nn36">Binding global data into the module.</a>
<li><a href="#Lua_nn37">Userdata and Metatables</a>
<li><a href="#Lua_nn38">Memory management</a>
</ul>
</ul>
</div>
<!-- INDEX -->
<p>
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 ISO C and C++). It's 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>
</p>
<p>
eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers the full implementation of the Lua programming language to the embedded world, extending it with specific features for efficient and portable software embedded development. eLua runs on smaller devices like microcontrollers and provides the full features of the regular Lua desktop version. More information on eLua can be found here: <a href="http://www.eluaproject.net">http://www.eluaproject.net</a>
</p>
<H2><a name="Lua_nn2">28.1 Preliminaries</a></H2>
<p>
The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. 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). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.
</p>
<H2><a name="Lua_nn3">28.2 Running SWIG</a></H2>
<p>
Suppose that you defined a SWIG module such as the following:
</p>
<div class="code"><pre>
%module example
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo;
</pre></div>
<p>
To build a Lua module, run SWIG using the <tt>-lua</tt> option.
</p>
<div class="shell"><pre>
$ swig -lua example.i
</pre></div>
<p>
If building a C++ extension, add the <tt>-c++</tt> option:
</p>
<div class="shell"><pre>
$ swig -c++ -lua example.i
</pre></div>
<p>
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.
</p>
<p>
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 wrapped 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.
</p>
<p>
To build an eLua module, run SWIG using <tt>-lua</tt> and add either <tt>-elua</tt> or <tt>-eluac</tt>.
</p>
<div class="shell"><pre>
$ swig -lua -elua example.i
</pre></div>
<p>
or
</p>
<div class="shell"><pre>
$ swig -lua -eluac example.i
</pre></div>
<p>
The <tt>-elua</tt> option puts all the C function wrappers and variable get/set wrappers in rotables. It also generates a metatable which will control the access to these variables from eLua. It also offers a significant amount of module size compression. On the other hand, the <tt>-eluac</tt> option puts all the wrappers in a single rotable. With this option, no matter how huge the module, it will consume no additional microcontroller SRAM (crass compression). There is a catch though: Metatables are not generated with <tt>-eluac</tt>. To access any value from eLua, one must directly call the wrapper function associated with that value.
</p>
<H3><a name="Lua_commandline">28.2.1 Additional command line options</a></H3>
<p>
The following table list the additional commandline options available for the Lua module. They can also be seen by using:
</p>
<div class="shell"><pre>
swig -lua -help
</pre></div>
<table summary="Lua specific options">
<tr>
<th>Lua specific options</th>
</tr>
<tr>
<td>-elua</td>
<td>Generates LTR compatible wrappers for smaller devices running elua.</td>
</tr>
<tr>
<td>-eluac</td>
<td>LTR compatible wrappers in "crass compress" mode for elua.</td>
</tr>
<tr>
<td>-nomoduleglobal</td>
<td>Do not register the module name as a global variable but return the module table from calls to require.</td>
</tr>
<tr>
<td>-no-old-metatable-bindings</td>
<td>Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included in appropriate later sections.</td>
</tr>
<tr>
<td>-squash-bases</td>
<td>Squashes symbols from all inheritance tree of a given class into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly speeds things up, but increases memory consumption.</td>
</tr>
</table>
<H3><a name="Lua_nn4">28.2.2 Compiling and Linking and Interpreter</a></H3>
<p>
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:
</p>
<div class="code"><pre>
#include &lt;stdio.h&gt;
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
extern int luaopen_example(lua_State* L); // declare the wrapped module
int main(int argc, char* argv[])
{
lua_State *L;
if (argc&lt;2)
{
printf("%s: &lt;filename.lua&gt;\n", argv[0]);
return 0;
}
L=lua_open();
luaopen_base(L); // load basic libs (eg. print)
luaopen_example(L); // load the wrapped module
if (luaL_loadfile(L, argv[1])==0) // load and run the file
lua_pcall(L, 0, 0, 0);
else
printf("unable to load %s\n", argv[1]);
lua_close(L);
return 0;
}
</pre></div>
<p>
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.
</p>
<p>
The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
</p>
<div class="shell"><pre>
$ swig -lua example.i -o example_wrap.c
$ gcc -I/usr/include/lua -c min.c -o min.o
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
</pre></div>
<p>
For eLua, the source must be built along with the wrappers generated by SWIG. Make sure the eLua source files <tt>platform_conf.h</tt> and <tt>auxmods.h</tt> are updated with the entries of your new module. Please note: <tt>"mod"</tt> is the module name.
</p>
<div class="code"><pre>
/* Sample platform_conf.h */
#define LUA_PLATFORM_LIBS_ROM\
_ROM( AUXLIB_PIO, luaopen_pio, pio_map )\
_ROM( AUXLIB_TMR, luaopen_tmr, tmr_map )\
_ROM( AUXLIB_MOD, luaopen_mod, mod_map )\
....
</pre></div>
<div class="code"><pre>
/* Sample auxmods.h */
#define AUXLIB_PIO "pio"
LUALIB_API int ( luaopen_pio )(lua_State *L );
#define AUXLIB_MOD "mod"
LUALIB_API int ( luaopen_mod )(lua_State *L );
....
</pre></div>
<p>
More information on building and configuring eLua can be found here: <a href="http://www.eluaproject.net/doc/v0.8/en_building.html">http://www.eluaproject.net/doc/v0.8/en_building.html</a>
</p>
<H3><a name="Lua_nn5">28.2.3 Compiling a dynamic module</a></H3>
<p>
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. Assuming you have code you need to link to in a file called <tt>example.c</tt>, the commands will be something like this:
</p>
<div class="shell"><pre>
$ swig -lua example.i -o example_wrap.c
$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -fPIC -c example.c -o example.o
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
</pre></div>
<p>
The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x and later. The loading is extremely simple.
</p>
<div class="targetlang"><pre>
require("example")
</pre></div>
<p>
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
</p>
<div class="targetlang"><pre>
my_init=loadlib("example.so", "luaopen_example") -- for Unix/Linux
--my_init=loadlib("example.dll", "luaopen_example") -- for Windows
assert(my_init) -- make sure it's not nil
my_init() -- call the init fn of the lib
</pre></div>
<p>
Or can be done in a single line of Lua code
</p>
<div class="targetlang"><pre>
assert(loadlib("example.so", "luaopen_example"))()
</pre></div>
<p>
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).
</p>
<div class="targetlang"><pre>
a, b, c=package.loadlib("example.so", "luaopen_example") -- for Unix/Linux
--a, b, c=package.loadlib("example.dll", "luaopen_example") -- for Windows
print(a, b, c)
</pre></div>
<p>
Note: for Lua 5.0:<br>
The loadlib() function is in the global namespace, not in a package. So it's just loadlib().
</p>
<p>
if 'a' is a function, this is all working fine, all you need to do is call it
</p>
<div class="targetlang"><pre>
a()
</pre></div>
<p>
to load your library which will add a table 'example' with all the functions added.
</p>
<p>
If it doesn't work, look at the error messages, in particular message 'b'<br>
<tt> The specified module could not be found.</tt><br>
Means that is cannot find the module, check your the location and spelling of the module.<br>
<tt> The specified procedure could not be found.</tt><br>
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>
<tt> 'loadlib' not installed/supported</tt><br>
Is quite obvious (Go back and consult the Lua documents on how to enable loadlib for your platform).
</p>
<H3><a name="Lua_nn6">28.2.4 Using your module</a></H3>
<p>
Assuming all goes well, you will be able to this:
</p>
<div class="targetlang"><pre>
$ ./my_lua
&gt; print(example.gcd(4, 6))
2
&gt; print(example.Foo)
3
&gt; example.Foo=4
&gt; print(example.Foo)
4
&gt;
</pre></div>
<H2><a name="Lua_nn7">28.3 A tour of basic C/C++ wrapping</a></H2>
<p>
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.
</p>
<H3><a name="Lua_nn8">28.3.1 Modules</a></H3>
<p>
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.
</p>
<H3><a name="Lua_nn9">28.3.2 Functions</a></H3>
<p>
Global functions are wrapped as new Lua built-in functions. For example,
</p>
<div class="code"><pre>
%module example
int fact(int n);</pre></div>
<p>
creates a built-in function <tt>example.fact(n)</tt> that works exactly like you think it does:
</p>
<div class="targetlang"><pre>
&gt; print example.fact(4)
24
&gt;
</pre></div>
<p>
To avoid name collisions, SWIG create a Lua table which keeps all the functions, constants, classes and global variables in.
It is possible to copy the functions, constants and classes (but not variables) 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.
This option is considered deprecated and will be removed in the near future.
</p>
<div class="targetlang"><pre>
&gt; for k, v in pairs(example) do _G[k]=v end
&gt; print(fact(4))
24
&gt;
</pre></div>
<p>
It is also possible to rename the module with an assignment.
</p>
<div class="targetlang"><pre>
&gt; e=example
&gt; print(e.fact(4))
24
&gt; print(example.fact(4))
24
</pre></div>
<H3><a name="Lua_nn10">28.3.3 Global variables</a></H3>
<p>
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:
</p>
<div class="code"><pre>%module example
extern double Foo;
</pre></div>
<p>
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.
</p>
<div class="targetlang"><pre>
&gt; print(example.Foo)
3
&gt; c=example.Foo -- c is a COPY of example.Foo, not the same thing
&gt; example.Foo=4
&gt; print(c)
3
&gt; c=5 -- this will not effect the original example.Foo
&gt; print(example.Foo, c)
4 5
</pre></div>
<p>
It 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.
</p>
<div class="targetlang"><pre>
&gt; e=example
&gt; -- e and example are the same table
&gt; -- so e.Foo and example.Foo are the same thing
&gt; example.Foo=4
&gt; print(e.Foo)
4
</pre></div>
<p>
If a variable is marked with the %immutable directive then any attempts to set this variable will cause a Lua error. Given a global variable:
</p>
<div class="code"><pre>%module example
%immutable;
extern double Foo;
%mutable;
</pre></div>
<p>
SWIG will allow the reading of <tt>Foo</tt> but when a set attempt is made, an error function will be called.
</p>
<div class="targetlang"><pre>
&gt; print(e.Foo) -- reading works ok
4
&gt; example.Foo=40 -- but writing does not
This variable is immutable
stack traceback:
[C]: ?
[C]: ?
stdin:1: in main chunk
[C]: ?
</pre></div>
<p>
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.
</p>
<p>
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.
</p>
<div class="targetlang"><pre>
&gt; -- example.PI does not exist
&gt; print(example.PI)
nil
&gt; example.PI=3.142 -- new value added
&gt; print(example.PI)
3.142
</pre></div>
<p>
If you have used the <tt>-eluac</tt> option for your eLua module, you will have to follow a different approach while manipulating global variables. (This is not applicable for wrappers generated with <tt>-elua</tt>)
</p>
<div class="targetlang"><pre>
&gt; -- Applicable only with -eluac. (num is defined)
&gt; print(example.num_get())
20
&gt; example.num_set(50) -- new value added
&gt; print(example.num_get())
50
</pre></div>
<p>
In general, functions of the form <tt>"variable_get()"</tt> and <tt>"variable_set()"</tt> are automatically generated by SWIG for use with <tt>-eluac</tt>.
</p>
<H3><a name="Lua_nn11">28.3.4 Constants and enums</a></H3>
<p>
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:
</p>
<div class="code"><pre>%module example
%constant int ICONST=42;
#define SCONST "Hello World"
enum Days{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
</pre></div>
<p>
This is 'effectively' converted into the following Lua code:
</p>
<div class="targetlang"><pre>
example.ICONST=42
example.SCONST="Hello World"
example.SUNDAY=0
....
</pre></div>
<p>
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.
</p>
<p>
If you're using eLua and have used <tt>-elua</tt> or <tt>-eluac</tt> to generate your wrapper, macro constants and enums should be accessed through a rotable called <tt>"const"</tt>. In eLua, macro constants and enums are guaranteed to remain constants since they are all contained within a rotable. A regular C constant is accessed from eLua just as if it were a regular global variable, just that the property of value immutability is demonstrated if an attempt at modifying a C constant is made.
</p>
<div class="targetlang"><pre>
&gt; print(example.ICONST)
10
&gt; print(example.const.SUNDAY)
0
&gt; print(example.const.SCONST)
Hello World
</pre></div>
<H4><a name="Lua_nn13">28.3.4.1 Constants/enums and classes/structures</a></H4>
<p>
Enums are exported into a class table. For example, given some enums:
</p>
<div class="code"><pre>%module example
enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
struct Test {
enum { TEST1 = 10, TEST2 = 20 };
#ifdef __cplusplus // There are no static members in C
static const int ICONST = 12;
#endif
};
</pre></div>
<p>
There is a slight difference in behaviour wrapping C and C++ code due to the different scoping rules of C and C++.
The wrapped C++ code is used as follows from Lua code:
</p>
<div class="targetlang"><pre>
&gt; print(example.SUNDAY)
0
&gt; print(example.Test.TEST1)
10
&gt; print(example.Test.ICONST)
12
</pre></div>
<p>Enums within a C struct are in the global namespace and are used as follows from Lua</p>
<div class="targetlang"><pre>
&gt; print(example.SUNDAY)
0
&gt; -- See the difference here
&gt; print(example.TEST1)
10
</pre></div>
<p>
<b>Compatibility Note:</b> Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above.
There is no change in the C wrappers, but
the following code was the only way to access these constants/enums when wrapping C++ member constants:
</p>
<div class="targetlang"><pre>
&gt; print(example.Test_TEST1)
10
&gt; print(example.Test_ICONST)
12
</pre></div>
<p>
The old-style bindings are still generated in addition to the new ones.
If the <tt>-no-old-metatable-bindings</tt> option is used, then these old-style bindings are not generated.
</p>
<p>
It is worth mentioning, that <tt>example.Test.TEST1</tt> and <tt>example.Test_TEST1</tt> are different entities and changing one does not change the other.
Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues.
</p>
<H3><a name="Lua_nn12">28.3.5 Pointers</a></H3>
<p>
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:
</p>
<div class="code"><pre>%module example
FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);
</pre></div>
<p>
When wrapped, you will be able to use the functions in a natural way from Lua. For example:
</p>
<div class="targetlang"><pre>
&gt; f=example.fopen("junk", "w")
&gt; example.fputs("Hello World", f)
&gt; example.fclose(f)
</pre></div>
<p>
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 wrapped object).
</p>
<div class="targetlang"><pre>
&gt; print(f)
userdata: 003FDA80
&gt; print(swig_type(f))
FILE * -- it's a FILE*
</pre></div>
<p>
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.
</p>
<div class="targetlang"><pre>
&gt; f=example.fopen("not there", "r") -- this will return a NULL in C
&gt; print(f)
nil
</pre></div>
<H3><a name="Lua_structures">28.3.6 Structures</a></H3>
<p>
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,
</p>
<div class="code"><pre>struct Point{
int x, y;
};
</pre></div>
<p>
is used as follows:
</p>
<div class="targetlang"><pre>
&gt; p=example.new_Point()
&gt; p.x=3
&gt; p.y=5
&gt; print(p.x, p.y)
3 5
&gt;
</pre></div>
<p>
Similar access is provided for unions and the data members of C++ classes.<br>
C structures can be created using a function <tt>new_Point()</tt>, and both C structures and C++ classes can be created using just the name <tt>Point()</tt>.
</p>
<p>
If you print out the value of p in the above example, you will see something like this:
</p>
<div class="targetlang"><pre>
&gt; print(p)
userdata: 003FA320
</pre></div>
<p>
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 effectively 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).
</p>
<p>
<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 immutables, setting attempts will be cause an error. For example:
</p>
<div class="code"><pre>struct Foo {
...
%immutable;
int x; // Read-only members
char *name;
%mutable;
...
};
</pre></div>
<p>
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).
</p>
<p>
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:
</p>
<div class="code"><pre>struct Foo {
int a;
};
struct Bar {
Foo f;
};
</pre></div>
<p>
Now, suppose that you access the f attribute of Bar like this:
</p>
<div class="targetlang"><pre>
&gt; b = Bar()
&gt; x = b.f
</pre></div>
<p>
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:
</p>
<div class="code"><pre>
Bar b;
Foo *x = &amp;b-&gt;f; // Points inside b
</pre></div>
<p>
Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:
</p>
<div class="targetlang"><pre>
&gt; b = Bar()
&gt; b.f.a = 3 -- Modify attribute of structure member
&gt; x = b.f
&gt; x.a = 3 -- Modifies the same structure
</pre></div>
<p>
For eLua with the <tt>-eluac</tt> option, structure manipulation has to be performed with specific structure functions generated by SWIG. Let's say you have the following structure definition:
</p>
<div class="code"><pre>struct data {
int x, y;
double z;
};
&gt; --From eLua
&gt; a = example.new_data()
&gt; example.data_x_set(a, 10)
&gt; example.data_y_set(a, 20)
&gt; print(example.data_x_get(a), example.data_y_get(a))
10 20
</pre></div>
<p>
In general, functions of the form <tt>"new_struct()"</tt>, <tt>"struct_member_get()"</tt>, <tt>"struct_member_set()"</tt> and <tt>"free_struct()"</tt> are automatically generated by SWIG for each structure defined in C. (Please note: This doesn't apply for modules generated with the <tt>-elua</tt> option)
</p>
<H3><a name="Lua_nn14">28.3.7 C++ classes</a></H3>
<p>
C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
</p>
<div class="code"><pre>class List {
public:
List();
~List();
int search(char *item);
void insert(char *item);
void remove(char *item);
char *get(int n);
int length;
};
</pre></div>
<p>
you can use it in Lua like this:
</p>
<div class="targetlang"><pre>
&gt; l = example.List()
&gt; l:insert("Ale")
&gt; l:insert("Stout")
&gt; l:insert("Lager")
&gt; print(l:get(1))
Stout
&gt; print(l:length)
3
&gt;
</pre></div>
<p>
(Note: for calling methods of a class, you use <tt>class:method(args)</tt>, not <tt>class.method(args)</tt>, it's an easy mistake to make. However for data attributes it is <tt>class.attribute</tt>)
</p>
<p>
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:
</p>
<div class="code"><pre>
class Spam {
public:
static void foo();
static int bar;
};
</pre></div>
<p>
In Lua, C++ static members can be accessed as follows:
</p>
<div class="targetlang"><pre>
&gt; example.Spam.foo() -- calling Spam::foo()
&gt; a=example.Spam.bar -- reading Spam::bar
&gt; example.Spam.bar=b -- writing to Spam::bar
</pre></div>
<p>
It is not (currently) possible to access static members of an instance:
</p>
<div class="targetlang"><pre>
&gt; s=example.Spam() -- s is a Spam instance
&gt; s.foo() -- Spam::foo() via an instance
-- does NOT work
</pre></div>
<p>
<b>Compatibility Note:</b> In versions prior to SWIG-3.0.0 only the following names would work:
</p>
<div class="targetlang"><pre>
&gt; example.Spam_foo() -- calling Spam::foo()
&gt; a=example.Spam_bar -- reading Spam::bar
&gt; example.Spam_bar=b -- writing to Spam::bar
</pre></div>
<p>
Both style names are generated by default now.
However, if the <tt>-no-old-metatable-bindings</tt> option is used, then the backward compatible names are not generated in addition to ordinary ones.
</p>
<H3><a name="Lua_nn15">28.3.8 C++ inheritance</a></H3>
<p>
SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
</p>
<div class="code"><pre>class Foo {
...
};
class Bar : public Foo {
...
};
</pre></div>
<p>
And if you have functions like this
</p>
<div class="code"><pre>void spam(Foo *f);
</pre></div>
<p>
then the function <tt>spam()</tt> accepts a Foo pointer or a pointer to any class derived from Foo.
</p>
<p>
It is safe to use multiple inheritance with SWIG.
</p>
<H3><a name="Lua_nn16">28.3.9 Pointers, references, values, and arrays</a></H3>
<p>
In C++, there are many different ways a function might receive and manipulate objects. For example:
</p>
<div class="code"><pre>void spam1(Foo *x); // Pass by pointer
void spam2(Foo &amp;x); // Pass by reference
void spam3(Foo x); // Pass by value
void spam4(Foo x[]); // Array of objects
</pre></div>
<p>
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:
</p>
<div class="targetlang"><pre>
&gt; f = Foo() -- Create a Foo
&gt; spam1(f) -- Ok. Pointer
&gt; spam2(f) -- Ok. Reference
&gt; spam3(f) -- Ok. Value.
&gt; spam4(f) -- Ok. Array (1 element)
</pre></div>
<p>
Similar behaviour occurs for return values. For example, if you had functions like this,
</p>
<div class="code"><pre>Foo *spam5();
Foo &amp;spam6();
Foo spam7();
</pre></div>
<p>
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.
</p>
<H3><a name="Lua_nn17">28.3.10 C++ overloaded functions</a></H3>
<p>
C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
</p>
<div class="code"><pre>void foo(int);
void foo(char *c);
</pre></div>
<p>
You can use them in Lua in a straightforward manner:
</p>
<div class="targetlang"><pre>
&gt; foo(3) -- foo(int)
&gt; foo("Hello") -- foo(char *c)
</pre></div>
<p>
However due to Lua's coercion mechanism is can sometimes do strange things.
</p>
<div class="targetlang"><pre>
&gt; foo("3") -- "3" can be coerced into an int, so it calls foo(int)!
</pre></div>
<p>
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).
</p>
<p>
Similarly, if you have a class like this,
</p>
<div class="code"><pre>class Foo {
public:
Foo();
Foo(const Foo &amp;);
...
};
</pre></div>
<p>
you can write Lua code like this:
</p>
<div class="targetlang"><pre>
&gt; f = Foo() -- Create a Foo
&gt; g = Foo(f) -- Copy f
</pre></div>
<p>
Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:
</p>
<div class="code"><pre>void spam(int);
void spam(short);
</pre></div>
<p>
or
</p>
<div class="code"><pre>void foo(Bar *b);
void foo(Bar &amp;b);
</pre></div>
<p>
If declarations such as these appear, you will get a warning message like this:
</p>
<div class="shell"><pre>
example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
example.i:11: Warning 509: as it is shadowed by spam(int).
</pre></div>
<p>
To fix this, you either need to ignore or rename one of the methods. For example:
</p>
<div class="code"><pre>%rename(spam_short) spam(short);
...
void spam(int);
void spam(short); // Accessed as spam_short
</pre></div>
<p>
or
</p>
<div class="code"><pre>%ignore spam(short);
...
void spam(int);
void spam(short); // Ignored
</pre></div>
<p>
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.
</p>
<p>
Please refer to the "SWIG and C++" chapter for more information about overloading.
</p>
<p>
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.
</p>
<H3><a name="Lua_nn18">28.3.11 C++ operators</a></H3>
<p>
Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
</p>
<div class="code"><pre>class Complex {
private:
double rpart, ipart;
public:
Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &amp;operator=(const Complex &amp;c);
Complex operator+(const Complex &amp;c) const;
Complex operator-(const Complex &amp;c) const;
Complex operator*(const Complex &amp;c) const;
Complex operator-() const;
double re() const { return rpart; }
double im() const { return ipart; }
};
</pre></div>
<p>
When wrapped, it works like you expect:
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; e:re()
10.0
&gt; e:im()
12.0
</pre></div>
<p>
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
</p>
<div class="code"><pre>
class Complex {
...
friend Complex operator+(double, const Complex &amp;c);
...
};
</pre></div>
<p>
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:
</p>
<div class="code"><pre>
%rename(Complex_add_dc) operator+(double, const Complex &amp;);
...
Complex operator+(double, const Complex &amp;c);
</pre></div>
<p>
There are ways to make this operator appear as part of the class using the <tt>%extend</tt> directive. Keep reading.
</p>
<p>
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>).
</p>
<p>
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).
<p>
The current list of operators which can be overloaded (and the alternative function names) are:<ul>
<li><tt>__add__</tt> operator+
<li><tt>__sub__</tt> operator-
<li><tt>__mul__</tt> operator *
<li><tt>__div__</tt> operator/
<li><tt>__unm__</tt> unary minus
<li><tt>__call__</tt> operator<tt>()</tt> (often used in functor classes)
<li><tt>__pow__</tt> the exponential fn (no C++ equivalent, Lua uses <tt>^</tt>)
<li><tt>__concat__</tt> the concatenation operator (Lua's <tt>..</tt>)
<li><tt>__eq__</tt> operator<tt>==</tt>
<li><tt>__lt__</tt> operator<tt>&lt;</tt>
<li><tt>__le__</tt> operator<tt>&lt;=</tt>
</ul>
<p>
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.
</p>
<p>
The following operators cannot be overloaded (mainly because they are not supported in Lua)<ul>
<li>++ and --<li>+=, -=, *= etc<li>% operator (you have to use math.mod)<li>assignment operator<li>all bitwise/logical operations</ul>
<p>
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
</p>
<div class="code"><pre>const char* __str__() {
static char buffer[255];
sprintf(buffer, "Complex(%g, %g)", this-&gt;re(), this-&gt;im());
return buffer;
}
</pre></div>
<p>
Then this will support the following code in Lua
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; print(e)
Complex(10, 12)
&gt; s=tostring(e) -- s is the number in string form
&gt; print(s)
Complex(10, 12)
</pre></div>
<p>
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>
</p>
<div class="code"><pre>class Complex {
//....
double __getitem__(int i)const; // i is the index, returns the data
void __setitem__(int i, double d); // i is the index, d is the data
};
</pre></div>
<p>
C++ operators are mapped to Lua predefined metafunctions. Class inherits from its bases the following list of metafunctions ( thus inheriting the folloging
operators and pseudo-operators):</p>
<ul>
<li><tt>__add__</tt>
<li><tt>__sub__</tt>
<li><tt>__mul__</tt>
<li><tt>__div__</tt>
<li><tt>__unm__</tt>
<li><tt>__mod__</tt>
<li><tt>__call__</tt>
<li><tt>__pow__</tt>
<li><tt>__concat__</tt>
<li><tt>__eq__</tt>
<li><tt>__lt__</tt>
<li><tt>__le__</tt>
<li><tt>__len__</tt>
<li><tt>__getitem__</tt>
<li><tt>__setitem__</tt>
<li><tt>__tostring</tt> used internally by Lua for tostring() function. __str__ is mapped to this function
</ul>
<p>No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. <tt>__tostring</tt> is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG.
</p>
<H3><a name="Lua_nn19">28.3.12 Class extension with %extend</a></H3>
<p>
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.
</p>
<p>
Take the original Complex class
</p>
<div class="code"><pre>class Complex {
private:
double rpart, ipart;
public:
Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &amp;operator=(const Complex &amp;c);
Complex operator+(const Complex &amp;c) const;
Complex operator-(const Complex &amp;c) const;
Complex operator*(const Complex &amp;c) const;
Complex operator-() const;
double re() const { return rpart; }
double im() const { return ipart; }
};
</pre></div>
<p>
Now we extend it with some new code
</p>
<div class="code"><pre>%extend Complex {
const char *__str__() {
static char tmp[1024];
sprintf(tmp, "Complex(%g, %g)", $self-&gt;re(), $self-&gt;im());
return tmp;
}
bool operator==(const Complex&amp; c) {
return ($self-&gt;re()==c.re() &amp;&amp; $self-&gt;im()==c.im());
}
};
</pre></div>
<p>
Now, in Lua
</p>
<div class="targetlang"><pre>
&gt; c = Complex(3, 4)
&gt; d = Complex(7, 8)
&gt; e = c + d
&gt; print(e) -- print uses __str__ to get the string form to print
Complex(10, 12)
&gt; print(e==Complex(10, 12)) -- testing the == operator
true
&gt; print(e!=Complex(12, 12)) -- the != uses the == operator
true
</pre></div>
<p>
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).
</p>
<H3><a name="Lua_nn20">28.3.13 Using %newobject to release memory</a></H3>
<p> If you have a function that allocates memory like this,</p>
<div class="code">
<pre>char *foo() {
char *result = (char *) malloc(...);
...
return result;
}
</pre>
</div>
<p> then the SWIG generated wrappers will have a memory leak--the
returned data will be copied into a string object and the old contents
ignored.</p>
<p> To fix the memory leak, use the <a href="Customization.html#Customization_ownership">%newobject directive</a>.</p>
<div class="code">
<pre>%newobject foo;
...
char *foo();
</pre>
</div>
<p> This will release the allocated memory.</p>
<H3><a name="Lua_nn21">28.3.14 C++ templates</a></H3>
<p>
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:
</p>
<div class="code"><pre>%module example
%{
#include "pair.h"
%}
template&lt;class T1, class T2&gt;
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair();
pair(const T1&amp;, const T2&amp;);
~pair();
};
%template(pairii) pair&lt;int, int&gt;;
</pre></div>
<p>
In Lua:
</p>
<div class="targetlang"><pre>
&gt; p = example.pairii(3, 4)
&gt; print(p.first, p.second)
3 4
</pre></div>
<p>
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.
</p>
<H3><a name="Lua_nn22">28.3.15 C++ Smart Pointers</a></H3>
<p>
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:
</p>
<div class="code"><pre>template&lt;class T&gt; class SmartPtr {
...
T *operator-&gt;();
...
}
</pre></div>
<p>
Then, if you have a class like this,
</p>
<div class="code"><pre>class Foo {
public:
int x;
int bar();
};
</pre></div>
<p>
A smart pointer would be used in C++ as follows:
</p>
<div class="code"><pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
...
p-&gt;x = 3; // Foo::x
int y = p-&gt;bar(); // Foo::bar
</pre></div>
<p>
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:
</p>
<div class="code"><pre>%module example
...
%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
...
</pre></div>
<p>
Now, in Lua, everything should just "work":
</p>
<div class="targetlang"><pre>
&gt; p = example.CreateFoo() -- Create a smart-pointer somehow
&gt; p.x = 3 -- Foo::x
&gt; print(p:bar()) -- Foo::bar
</pre></div>
<p>
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:
</p>
<div class="targetlang"><pre>
&gt; f = p:__deref__() -- Returns underlying Foo *
</pre></div>
<H3><a name="Lua_nn23">28.3.16 C++ Exceptions</a></H3>
<p>
Lua does not natively support exceptions, but it has errors which are similar. When a Lua function terminates with an error
it returns one value back to the caller. SWIG automatically maps any basic type which is thrown into a Lua error.
Therefore for a function:
</p>
<div class="code"><pre>
int message() throw(const char *) {
throw("I died.");
return 1;
}
</pre></div>
<p>
SWIG will automatically convert this to a Lua error.
</p>
<div class="targetlang"><pre>
&gt; message()
I died.
stack traceback:
[C]: in function 'message'
stdin:1: in main chunk
[C]: ?
&gt;
</pre></div>
<p>
If you want to catch an exception, you must use either pcall() or xpcall(), which are documented in the Lua manual.
Using xpcall will allow you to obtain additional debug information (such as a stacktrace).
</p>
<div class="targetlang"><pre>
&gt; function a() b() end -- function a() calls function b()
&gt; function b() message() end -- function b() calls C++ function message(), which throws
&gt; ok, res=pcall(a) -- call the function
&gt; print(ok, res)
false I died.
&gt; ok, res=xpcall(a, debug.traceback) -- call the function
&gt; print(ok, res)
false I died.
stack traceback:
[C]: in function 'message'
runme.lua:70: in function 'b'
runme.lua:67: in function &lt;runme.lua:66&gt;
[C]: in function 'xpcall'
runme.lua:95: in main chunk
[C]: ?
</pre></div>
<p>
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 an error string. </p>
<p>
However it's not so simple to throw other types of objects.
Thrown objects are not valid outside the 'catch' block. Therefore they cannot be
returned to the interpreter.
The obvious ways to overcome this would be to either return a copy of the object, or to convert the object to a string and
return that. Though it seems obvious to perform the former, in some cases this is not possible, most notably when
SWIG has no information about the object, or the object is not copyable/creatable.
</p>
<p>
Therefore by default SWIG converts all thrown object into strings and returns them. So given a function:
</p>
<div class="code"><pre>
void throw_A() throw(A*) {
throw new A();
}
</pre></div>
<p>
SWIG will just convert it (poorly) to a string and use that as its error. (This is not that useful, but it always works).
</p>
<div class="targetlang"><pre>
&gt; throw_A()
object exception:A *
stack traceback:
[C]: in function 'unknown'
stdin:1: in main chunk
[C]: ?
&gt;
</pre></div>
<p>
To get a more useful behaviour out of SWIG you must either: provide a way to convert your exceptions into strings, or
throw objects which can be copied.
</p>
<p>
If you have your own class which you want output as a string you will need to add a typemap something like this:
</p>
<div class="code"><pre>
%typemap(throws) my_except
%{
lua_pushstring(L, $1.what()); // assuming my_except::what() returns a const char* message
SWIG_fail; // trigger the error handler
%}
</pre></div>
<p>
If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have an additional
<tt>%apply</tt> statement, to tell SWIG to return a copy of this object to the interpreter. For example:
</p>
<div class="code"><pre>
%apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
class Exc {
public:
Exc(int c, const char *m) {
code = c;
strncpy(msg, m, 256);
}
int code;
char msg[256];
};
void throw_exc() throw(Exc) {
throw(Exc(42, "Hosed"));
}
</pre></div>
<p>
Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
</p>
<div class="targetlang"><pre>
&gt; ok, res=pcall(throw_exc)
&gt; print(ok)
false
&gt; print(res)
userdata: 0003D880
&gt; print(res.code, res.msg)
42 Hosed
&gt;
</pre></div>
<p>
Note: it is also possible (though tedious) to have a function throw several different kinds of exceptions. To process this
will require a pcall, followed by a set of if statements checking the type of the error.
</p>
<p>
All of this code assumes that your C++ code uses exception specification (which a lot doesn't).
If it doesn't consult the "<a href="SWIGPlus.html#SWIGPlus_catches">Exception handling with %catches</a>" section
and the "<a href="Customization.html#Customization_exception">Exception handling with %exception</a>" section, for more details on how to
add exception specification to functions or globally (respectively).
</p>
<H3><a name="Lua_namespaces">28.3.17 Namespaces </a></H3>
<p>
Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature.
</p>
<p> Namespaces are mapped into Lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code:
</p>
<div class="code"><pre>%module example
%nspace MyWorld::Nested::Dweller;
%nspace MyWorld::World;
int module_function() { return 7; }
int module_variable = 9;
namespace MyWorld {
class World {
public:
World() : world_max_count(9) {}
int create_world() { return 17; }
const int world_max_count; // = 9
};
namespace Nested {
class Dweller {
public:
enum Gender { MALE = 0, FEMALE = 1 };
static int count() { return 19; }
};
}
}
</pre></div>
<p>
Now, from Lua usage is as follows:
</p>
<div class="targetlang"><pre>
&gt; print(example.module_function())
7
&gt; print(example.module_variable)
9
&gt; print(example.MyWorld.World():create_world())
17
&gt; print(example.MyWorld.World.world_max_count)
9
&gt; print(example.MyWorld.Nested.Dweller.MALE)
0
&gt; print(example.MyWorld.Nested.Dweller.count())
19
&gt;
</pre></div>
<H4><a name="Lua_nn27">28.3.17.1 Compatibility Note </a></H4>
<p>
If SWIG is running in a backwards compatible way, i.e. without the <tt>-no-old-metatable-bindings</tt> option, then additional old-style names are generated (notice the underscore):
</p>
<div class="targetlang"><pre>
9
&gt; print(example.MyWorld.Nested.Dweller_MALE)
0
&gt; print(example.MyWorld.Nested.Dweller_count())
11
&gt;
</pre></div>
<H4><a name="Lua_nn29">28.3.17.2 Names </a></H4>
<p> If SWIG is launched without <tt>-no-old-metatable-bindings</tt> option, then it enters backward-compatible mode. While in this mode, it tries
to generate additional names for static functions, class static constants and class enums.
Those names are in a form <tt>$classname_$symbolname</tt> and are added to the scope surrounding the class.
If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled,
then module is considered a class namespace.</p>
<p> Consider the following C++ code </p>
<div class="code"><pre>%module example
%nspace MyWorld::Test;
namespace MyWorld {
class Test {
public:
enum { TEST1 = 10, TEST2 }
static const int ICONST = 12;
};
class Test2 {
public:
enum { TEST3 = 20, TEST4 }
static const int ICONST2 = 23;
}
</pre></div>
<p> When in backward compatible mode, in addition to the usual names, the following ones will be generated (notice the underscore):</p>
<div class="targetlang"><pre>
9
&gt; print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled
10
&gt; print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled
12
&gt; print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled
20
&gt; print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled
23
&gt;
</pre></div>
<p> There is a slight difference with enums when in C mode. As per C standard, enums from C structures are exported to
surrounding scope without any prefixing. Pretending that Test2 is a struct, not class, that would be:</p>
<div class="targetlang"><pre>
&gt; print(example.TEST3) -- NOT Test2_TEST3
20
&gt;
</pre></div>
<H4><a name="Lua_nn30">28.3.17.3 Inheritance </a></H4>
<p> The internal organization of inheritance has changed.
Consider the following C++ code:</p>
<div class="code"><pre>%module example
class Base {
public:
int base_func()
};
class Derived : public Base {
public:
int derived_func()
}
</pre></div>
<p>Lets assume for a moment that class member functions are stored in <tt>.fn</tt> table. Previously, when classes
were exported to Lua during module initialization, for every derived class all service tables <tt>ST(i.e. ".fn")</tt>
were squashed and added to corresponding derived class <tt>ST</tt>: Everything from <tt>.fn</tt> table of class Base
was copied to <tt>.fn</tt> table of class Derived and so on. This was a recursive procedure, so in the end the whole
inheritance tree of derived class was squashed into derived class. </p>
<p> That means that any changes done to class Base after module initialization wouldn't affect class Derived:</p>
<div class="targetlang"><pre>
base = example.Base()
der = example.Derived()
&gt; print(base.base_func)
function: 0x1367940
&gt; getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!)
&gt; print(base.new_func) -- Checking this function
function
&gt; print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more.
nil
&gt;
</pre></div>
<p> This behaviour was changed. Now unless -squash-bases option is provided, Derived store a list of it's bases and if some symbol is not found in it's own service tables
then its bases are searched for it. Option -squash-bases will effectively return old behaviour.
</p>
<div class="targetlang"><pre>
&gt; print(der.new_func) -- Now it works
function
&gt;
</pre></div>
<H2><a name="Lua_nn24">28.4 Typemaps</a></H2>
<p>This section explains what typemaps are and how to use them. The default wrapping 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 wrapping. This section will be explaining how to use typemaps to best effect</p>
<H3><a name="Lua_nn25">28.4.1 What is a typemap?</a></H3>
<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>
<div class="code"><pre>%module example
%typemap(in) int {
$1 = (int) lua_tonumber(L, $input);
printf("Received an integer : %d\n", $1);
}
%inline %{
extern int fact(int n);
%}
</pre></div>
<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>
<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>
<p>When this example is compiled into a Lua module, it operates as follows:</p>
<div class="targetlang"><pre>&gt; require "example"
&gt; print(example.fact(6))
Received an integer : 6
720
</pre></div>
<H3><a name="Lua_nn26">28.4.2 Using typemaps</a></H3>
<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>
<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>
<div class="code"><pre>void add(int x, int y, int *result) {
*result = x + y;
}
int sub(int *x1, int *y1) {
return *x1-*y1;
}
void swap(int *sx, int *sy) {
int t=*sx;
*sx=*sy;
*sy=t;
}
</pre></div>
<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>
<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>
<div class="code"><pre>%include &lt;typemaps.i&gt;
%apply int* OUTPUT {int *result}; // int *result is output
%apply int* INPUT {int *x1, int *y1}; // int *x1 and int *y1 are input
%apply int* INOUT {int *sx, int *sy}; // int *sx and int *sy are input and output
void add(int x, int y, int *result);
int sub(int *x1, int *y1);
void swap(int *sx, int *sy);
</pre></div>
<p>When wrapped, it gives the following results:</p>
<div class="targetlang"><pre>&gt; require "example"
&gt; print(example.add(1, 2))
3
&gt; print(demo.sub(1, 2))
-1
&gt; a, b=1, 2
&gt; c, d=demo.swap(a, b)
&gt; print(a, b, c, d)
1 2 2 1
</pre></div>
<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>
<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>
<H3><a name="Lua_typemap_arrays">28.4.3 Typemaps and arrays</a></H3>
<p>Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor
does SWIG have any indication of how large an array should be. However with the proper guidance SWIG can easily wrapper
arrays for convenient usage.</p>
<p>Given the functions:</p>
<div class="code"><pre>extern void sort_int(int* arr, int len);
extern void sort_double(double* arr, int len);
</pre></div>
<p>There are basically two ways that SWIG can deal with this. The first way, uses the <tt>&lt;carrays.i&gt;</tt> library
to create an array in C/C++ then this can be filled within Lua and passed into the function. It works, but it's a bit tedious.
More details can be found in the <a href="Library.html#Library_carrays">carrays.i</a> documentation.</p>
<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 %apply in the correct manner.</p>
<p>The wrapper file below, shows both the use of carrays as well as the use of the typemap to wrap arrays. </p>
<div class="code"><pre>// using the C-array
%include &lt;carrays.i&gt;
// this declares a batch of function for manipulating C integer arrays
%array_functions(int, int)
extern void sort_int(int* arr, int len); // the function to wrap
// using typemaps
%include &lt;typemaps.i&gt;
%apply (double *INOUT, int) {(double* arr, int len)};
extern void sort_double(double* arr, int len); // the function to wrap
</pre></div>
<p>Once wrapped, the functions can both be called, though with different ease of use:</p>
<div class="targetlang"><pre>require "example"
ARRAY_SIZE=10
-- passing a C array to the sort_int()
arr=example.new_int(ARRAY_SIZE) -- create the array
for i=0, ARRAY_SIZE-1 do -- index 0..9 (just like C)
example.int_setitem(arr, i, math.random(1000))
end
example.sort_int(arr, ARRAY_SIZE) -- call the function
example.delete_int(arr) -- must delete the allocated memory
-- use a typemap to call with a Lua-table
-- one item of note: the typemap creates a copy, rather than edit-in-place
t={} -- a Lua table
for i=1, ARRAY_SIZE do -- index 1..10 (Lua style)
t[i]=math.random(1000)/10
end
t=example.sort_double(t) -- replace t with the result
</pre></div>
<p>Obviously the first version could be made less tedious by writing a Lua function to perform the conversion from a table
to a C-array. The <tt>%luacode</tt> directive is good for this. See SWIG\Examples\lua\arrays for an example of this.</p>
<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
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>
<p>Note: SWIG also can support arrays of pointers in a similar manner.</p>
<H3><a name="Lua_typemaps_ptr_ptr_functions">28.4.4 Typemaps and pointer-pointer functions</a></H3>
<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>
<div class="code"><pre>struct iMath; // some structure
int Create_Math(iMath** pptr); // its creator (assume it mallocs)
</pre></div>
<p>Which would be used with the following C code:</p>
<div class="code"><pre>iMath* ptr;
int ok;
ok=Create_Math(&amp;ptr);
// do things with ptr
//...
free(ptr); // dispose of iMath
</pre></div>
<p>SWIG has a ready written typemap to deal with such a kind of function in &lt;typemaps.i&gt;. It provides the correct wrapping as well as setting the flag to inform Lua that the object in question should be garbage collected. Therefore the code is simply:</p>
<div class="code"><pre>%include &lt;typemaps.i&gt;
%apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG it's an output
struct iMath; // some structure
int Create_Math(iMath** pptr); // its creator (assume it mallocs)
</pre></div>
<p>The usage is as follows:</p>
<div class="targetlang"><pre>ok, ptr=Create_Math() -- ptr is an iMath* which is returned with the int (ok)
ptr=nil -- the iMath* will be GC'ed as normal
</pre></div>
<H2><a name="Lua_writing_typemaps">28.5 Writing typemaps</a></H2>
<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>
<p>Before proceeding, it should be stressed that writing typemaps is rarely needed unless you want to change some aspect of the wrapping, or to achieve an effect which in not available with the default bindings.</p>
<p>Before proceeding, you should read the previous section on using typemaps, and look at the existing 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 an idea to base your work on).</p>
<H3><a name="Lua_typemaps_write">28.5.1 Typemaps you can write</a></H3>
<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>
<ul>
<li><tt>in</tt> this is for input arguments to functions</li>
<li><tt>out</tt> this is for return types from functions</li>
<li><tt>argout</tt> this is for a function argument which is actually returning something</li>
<li><tt>typecheck</tt> this is used to determine which overloaded function should be called
(the syntax for the typecheck is different from the typemap, see typemaps for details).</li>
</ul>
<H3><a name="Lua_nn31">28.5.2 SWIG's Lua-C API</a></H3>
<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>
<p><tt>int SWIG_ConvertPtr(lua_State* L, int index, void** ptr, swig_type_info *type, int flags);</tt></p>
<div class="indent">
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 necessary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer.
If flags is set to SWIG_POINTER_DISOWN, this is will clear any ownership flag set on the object.<br>
This returns a value which can be checked with the macro SWIG_IsOK()
</div>
<p><tt>void SWIG_NewPointerObj(lua_State* L, void* ptr, swig_type_info *type, int own);</tt></p>
<div class="indent">
This is the opposite of SWIG_ConvertPtr, as it pushes a new userdata which wrappers the pointer 'ptr' of type 'type'.
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.
</div>
<p><tt>void* SWIG_MustGetPtr(lua_State* L, int index, swig_type_info *type, int flags, int argnum, const char* func_name);</tt></p>
<div class="indent">
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.
</div>
<p><tt>SWIG_fail</tt></p>
<div class="indent">
This macro, when called within the context of a SWIG wrapped 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>
A common use for this code is:<br><pre>
if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
lua_pushstring(L, "something bad happened");
SWIG_fail;
}</pre></div>
<p><tt>SWIG_fail_arg(char* func_name, int argnum, char* type)</tt></p>
<div class="indent">
This macro, when called within the context of a SWIG wrapped function, will display the error message and jump to the error handler code. The error message is of the form
<pre>
"Error in <i>func_name</i> (arg <i>argnum</i>), expected '<i>type</i>' got '<i>whatever the type was</i>'"
</pre></div>
<p><tt>SWIG_fail_ptr(const char* fn_name, int argnum, swig_type_info* type);</tt></p>
<div class="indent">
Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.</div>
<H2><a name="Lua_nn32">28.6 Customization of your Bindings</a></H2>
<p>
This section covers adding of some small extra bits to your module to add the last finishing touches.
</p>
<H3><a name="Lua_nn33">28.6.1 Writing your own custom wrappers</a></H3>
<p>
Sometimes, it may be necessary to add your own special functions, which bypass the normal SWIG wrapper 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:
</p>
<div class="code"><pre>%native(my_func) int native_function(lua_State*L); // registers native_function() with SWIG
...
%{
int native_function(lua_State*L) // my native code
{
...
}
%}
</pre></div>
<p>
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 wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.
</p>
<H3><a name="Lua_nn34">28.6.2 Adding additional Lua code</a></H3>
<p>
As well as adding additional C/C++ code, it's also possible to add your own Lua code to the module as well.
This code is executed once all other initialisation, including the %init code has been called.
</p>
<p>
The directive <tt>%luacode</tt> adds code into the module which is executed upon loading. Normally you would
use this to add your own functions to the module. Though you could easily perform other tasks.
</p>
<div class="code"><pre>%module example;
%luacode {
function example.greet()
print "hello world"
end
print "Module loaded ok"
}
...
%}
</pre></div>
<p>
Notice that the code is not part of the module table. Therefore any references to the module must have the
module name added.
</p>
<p>
Should there be an error in the Lua code, this will <em>not</em> stop loading of the module.
The default behaviour of SWIG is to print an error message to stderr and then continue.
It is possible to change this behaviour by using a <tt>#define SWIG_DOSTRING_FAIL(STR)</tt> to
define a different behaviour should the code fail.
</p>
<p>
Good uses for this feature is adding of new code, or writing helper functions to simplify some of the code.
See Examples/lua/arrays for an example of this code.
</p>
<H2><a name="Lua_nn35">28.7 Details on the Lua binding</a></H2>
<p>
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.
</p>
<p>
<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. It's mainly for people who need to know what's going on within the code.
</i>
</p>
<H3><a name="Lua_nn36">28.7.1 Binding global data into the module.</a></H3>
<p>
Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
</p>
<div class="code"><pre>%module example;
extern double Foo;
</pre></div>
<p>
SWIG will effectively generate the pair of functions
</p>
<div class="code"><pre>void Foo_set(double);
double Foo_get();
</pre></div>
<p>
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.
</p>
<div class="targetlang"><pre>
&gt; print(example)
table: 003F8F90
&gt; m=getmetatable(example)
&gt; table.foreach(m, print)
.set table: 003F9088
.get table: 003F9038
__index function: 003F8FE0
__newindex function: 003F8FF8
&gt; g=m['.get']
&gt; table.foreach(g, print)
Foo function: 003FAFD8
&gt;
</pre></div>
<p>
The .get and .set tables are lookups connecting the variable name 'Foo' to the accessor/mutator functions (Foo_set, Foo_get)
</p>
<p>
The Lua equivalent of the code for the <tt>__index</tt> and <tt>__newindex</tt> looks a bit like this
</p>
<div class="targetlang"><pre>
function __index(mod, name)
local g=getmetatable(mod)['.get'] -- gets the table
if not g then return nil end
local f=g[name] -- looks for the function
-- calls it &amp; returns the value
if type(f)=="function" then return f() end
return nil
end
function __newindex(mod, name, value)
local s=getmetatable(mod)['.set'] -- gets the table
if not s then return end
local f=s[name] -- looks for the function
-- calls it to set the value
if type(f)=="function" then f(value)
else rawset(mod, name, value) end
end
</pre></div>
<p>
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)'.
</p>
<H3><a name="Lua_nn37">28.7.2 Userdata and Metatables</a></H3>
<p>
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.
</p>
<p>
The metatable is a Lua 5.0 feature (which is also why SWIG cannot wrap Lua 4.0). It's 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.
</p>
<p>
Given a class
</p>
<div class="code"><pre>%module excpp;
class Point
{
public:
int x, y;
Point(){x=y=0;}
~Point(){}
virtual void Print(){printf("Point @%p (%d, %d)\n", this, x, y);}
};
</pre></div>
<p>
SWIG will create a module excpp, with all the various functions inside. However to allow the intuitive use of the userdata, SWIG 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 a new object is instantiated, the metatable is found in the registry and the userdata associated with the metatable. Currently, derived classes make a complete copy of the base class' table and then add on their own additional functions.
</p>
<p>
Some of the internals can be seen by looking at the metatable of a class:
</p>
<div class="targetlang"><pre>
&gt; p=excpp.Point()
&gt; print(p)
userdata: 003FDB28
&gt; m=getmetatable(p)
&gt; table.foreach(m, print)
.type Point
__gc function: 003FB6C8
__newindex function: 003FB6B0
__index function: 003FB698
.get table: 003FB4D8
.set table: 003FB500
.fn table: 003FB528
</pre></div>
<p>
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 class' destructor function)
</p>
<p>
The Lua equivalent of the code for enabling functions looks a little like this
</p>
<div class="targetlang"><pre>
function __index(obj, name)
local m=getmetatable(obj) -- gets the metatable
if not m then return nil end
local g=m['.get'] -- gets the attribute table
if not g then return nil end
local f=g[name] -- looks for the get_attribute function
-- calls it &amp; returns the value
if type(f)=="function" then return f() end
-- ok, so it not an attribute, maybe it's a function
local fn=m['.fn'] -- gets the function table
if not fn then return nil end
local f=fn[name] -- looks for the function
-- if found the fn then return the function
-- so the interpreter can call it
if type(f)=="function" then return f end
return nil
end
</pre></div>
<p>
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)'
</p>
<p>
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.
</p>
<p>
Note: Both the opaque structures (like the FILE*) and normal wrapped 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.
</p>
<p>
Note: Operator overloads are basically done in the same way, by adding functions such as '__add' &amp; '__call' to the class' 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.
</p>
<H3><a name="Lua_nn38">28.7.3 Memory management</a></H3>
<p>
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 wrapped 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) it will then call the destructor on the pointer.
</p>
<p>
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.
</p>
<p>
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).
</p>
</body>
</html>