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

« back to all changes in this revision

Viewing changes to Doc/Manual/Lua.html

  • Committer: Bazaar Package Importer
  • Author(s): Michael Vogt
  • Date: 2008-06-20 18:33:37 UTC
  • mfrom: (1.2.7 upstream)
  • Revision ID: james.westby@ubuntu.com-20080620183337-hockvwcewu29409c
Tags: 1.3.35-4ubuntu1
* Merge from debian unstable, remaining changes:
  - Drop support for pike.
  - Use python2.5 instead of python2.4.
  - use php5
  - Clean Runtime/ as well.
  - Force a few environment variables.
  - debian/Rules (clean): Remove Lib/ocaml/swigp4.ml.

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
<li><a href="#Lua_nn19">Class extension with %extend</a>
34
34
<li><a href="#Lua_nn20">C++ templates</a>
35
35
<li><a href="#Lua_nn21">C++ Smart Pointers</a>
36
 
<li><a href="#Lua_nn22">Writing your own custom wrappers</a>
 
36
<li><a href="#Lua_nn22">C++ Exceptions</a>
 
37
<li><a href="#Lua_nn23">Writing your own custom wrappers</a>
 
38
<li><a href="#Lua_nn24">Adding additional Lua code</a>
37
39
</ul>
38
 
<li><a href="#Lua_nn23">Details on the Lua binding</a>
 
40
<li><a href="#Lua_nn25">Details on the Lua binding</a>
39
41
<ul>
40
 
<li><a href="#Lua_nn24">Binding global data into the module.</a>
41
 
<li><a href="#Lua_nn25">Userdata and Metatables</a>
42
 
<li><a href="#Lua_nn26">Memory management</a>
 
42
<li><a href="#Lua_nn26">Binding global data into the module.</a>
 
43
<li><a href="#Lua_nn27">Userdata and Metatables</a>
 
44
<li><a href="#Lua_nn28">Memory management</a>
43
45
</ul>
44
46
</ul>
45
47
</div>
86
88
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.
87
89
</p>
88
90
<p>
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.
 
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 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.
90
92
</p>
91
93
<H3><a name="Lua_nn4"></a>22.2.1 Compiling and Linking and Interpreter</H3>
92
94
 
100
102
#include "lualib.h"
101
103
#include "lauxlib.h"
102
104
 
103
 
extern int luaopen_example(LuaState* L); // declare the wrapped module
 
105
extern int luaopen_example(lua_State* L); // declare the wrapped module
104
106
 
105
107
int main(int argc,char* argv[])
106
108
{
125
127
A much improved set of code can be found in the Lua distribution <tt>src/lua/lua.c</tt>. Include your module, just add the external declaration &amp; add a <tt>#define LUA_EXTRALIBS {"example",luaopen_example}</tt>, at the relevant place.
126
128
</p>
127
129
<p>
128
 
The exact commands for doing this vary from platform to platform. Here is a possible set of commands of doing this:
 
130
The exact commands for compiling and linking vary from platform to platform. Here is a possible set of commands of doing this:
129
131
</p>
130
132
<div class="shell"><pre>
131
 
$ swig -lua example.i
 
133
$ swig -lua example.i -o example_wrap.c
132
134
$ gcc -I/usr/include/lua -c min.c -o min.o
133
135
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
134
136
$ gcc -c example.c -o example.o
142
144
Most, but not all platforms support the dynamic loading of modules (Windows &amp; Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can  be used. The commands will be something like this:
143
145
</p>
144
146
<div class="shell"><pre>
145
 
$ swig -lua example.i
 
147
$ swig -lua example.i -o example_wrap.c
146
148
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
147
149
$ gcc -c example.c -o example.o
148
150
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
308
310
4
309
311
</pre></div>
310
312
<p>
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:
 
313
If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Lua error. Given a global variable:
312
314
</p>
313
315
 
314
316
<div class="code"><pre>%module example
331
333
        [C]: ?
332
334
</pre></div>
333
335
<p>
334
 
For those people who would rather that SWIG silently ignore the setting of immutables (as previous versions of the lua bindings did), adding a <tt>-DSWIGLUA_IGNORE_SET_IMMUTABLE</tt> compile option will remove this.
 
336
For those people who would rather that SWIG silently ignore the setting of immutables (as previous versions of the Lua bindings did), adding a <tt>-DSWIGLUA_IGNORE_SET_IMMUTABLE</tt> compile option will remove this.
335
337
</p>
336
338
<p>
337
339
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.
949
951
&gt; f = p:__deref__()     -- Returns underlying Foo *
950
952
</pre></div>
951
953
 
952
 
<H3><a name="Lua_nn22"></a>22.3.15 Writing your own custom wrappers</H3>
953
 
 
954
 
 
955
 
<p>
956
 
Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native lua-c API calls. These 'native' functions allow direct adding of your own code into the module. This is performed with the <tt>%native</tt> directive as follows:
957
 
</p>
958
 
<div class="code"><pre>%native(my_func) int native_function(lua_State*L);  // registers it with SWIG
 
954
<H3><a name="Lua_nn22"></a>22.3.15 C++ Exceptions</H3>
 
955
 
 
956
 
 
957
<p>
 
958
Lua does not natively support exceptions, but it has errors which are similar. When a Lua function terminates with an error
 
959
it returns one value back to the caller. SWIG automatically maps any basic type which is thrown into a Lua error.
 
960
Therefore for a function:
 
961
</p>
 
962
<div class="code"><pre>
 
963
int message() throw(const char *) {
 
964
  throw("I died.");
 
965
  return 1;
 
966
}
 
967
</pre></div>
 
968
<p>
 
969
SWIG will automatically convert this to a Lua error.
 
970
</p>
 
971
 
 
972
<div class="targetlang"><pre>
 
973
> message()
 
974
I died.
 
975
stack traceback:
 
976
        [C]: in function 'message'
 
977
        stdin:1: in main chunk
 
978
        [C]: ?
 
979
>
 
980
</pre></div>
 
981
 
 
982
<p>
 
983
If you want to catch an exception, you must use either pcall() or xpcall(), which are documented in the Lua manual.
 
984
Using xpcall will allow you to obtain additional debug information (such as a stacktrace).
 
985
</p>
 
986
 
 
987
<div class="targetlang"><pre>
 
988
> function a() b() end -- function a() calls function b()
 
989
> function b() message() end -- function b() calls C++ function message(), which throws 
 
990
> ok,res=pcall(a)  -- call the function
 
991
> print(ok,res)
 
992
false   I died.
 
993
> ok,res=xpcall(a,debug.traceback)  -- call the function
 
994
> print(ok,res)
 
995
false   I died.
 
996
stack traceback:
 
997
        [C]: in function 'message'
 
998
        runme.lua:70: in function 'b'
 
999
        runme.lua:67: in function &lt;runme.lua:66&gt;
 
1000
        [C]: in function 'xpcall'
 
1001
        runme.lua:95: in main chunk
 
1002
        [C]: ?
 
1003
</pre></div>
 
1004
 
 
1005
<p>
 
1006
SWIG is able to throw numeric types, enums, chars, char*'s and std::string's without problem.
 
1007
However its not so simple for to throw objects. 
 
1008
Thrown objects are not valid outside the 'catch' block. Therefore they cannot be
 
1009
returned to the interpreter. 
 
1010
The obvious ways to overcome this would be to either return a copy of the object, or so convert the object to a string and
 
1011
return that. Though it seems obvious to perform the former, in some cases this is not possible, most notably when
 
1012
SWIG has no information about the object, or the object is not copyable/creatable.
 
1013
</p>
 
1014
<p>
 
1015
Therefore by default SWIG converts all thrown object into strings and returns them. So given a function:
 
1016
</p>
 
1017
 
 
1018
<div class="code"><pre>
 
1019
void throw_A() throw(A*) {
 
1020
  throw new A();
 
1021
}
 
1022
</pre></div>
 
1023
<p>
 
1024
SWIG will just convert it (poorly) to a string and use that as its error. (Yes its not that useful, but it always works).
 
1025
</p>
 
1026
 
 
1027
<div class="targetlang"><pre>
 
1028
> throw_A()
 
1029
object exception:A *
 
1030
stack traceback:
 
1031
        [C]: in function 'unknown'
 
1032
        stdin:1: in main chunk
 
1033
        [C]: ?
 
1034
>
 
1035
</pre></div>
 
1036
<p>
 
1037
To get a more useful behaviour out of SWIG you must either: provide a way to convert your exceptions into strings, or
 
1038
throw objects which can be copied.
 
1039
</p>
 
1040
<p>
 
1041
SWIG has typemaps for std::exception and its children already written, so a function which throws any of these will
 
1042
automatically have its exception converted into an error string.
 
1043
</p>
 
1044
<p>
 
1045
If you have your own class which you want output as a string you will need to add a typemap something like this:
 
1046
</p>
 
1047
<div class="code"><pre>
 
1048
%typemap(throws) my_except
 
1049
%{ 
 
1050
  lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
 
1051
  SWIG_fail; // trigger the error handler
 
1052
%}
 
1053
</pre></div>
 
1054
<p>
 
1055
If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have and additional
 
1056
<tt>%apply</tt> statement, to inform SWIG to return a copy of this object to the interpreter. For example:
 
1057
</p>
 
1058
<div class="code"><pre>
 
1059
%apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
 
1060
 
 
1061
class Exc {
 
1062
public:
 
1063
  Exc(int c, const char *m) {
 
1064
    code = c;
 
1065
    strncpy(msg,m,256);
 
1066
  }
 
1067
  int code;
 
1068
  char msg[256];
 
1069
};
 
1070
 
 
1071
void throw_exc() throw(Exc) {
 
1072
  throw(Exc(42,"Hosed"));
 
1073
 
1074
</pre></div>
 
1075
<p>
 
1076
Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
 
1077
</p>
 
1078
<div class="targetlang"><pre>
 
1079
> ok,res=pcall(throw_exc)
 
1080
> print(ok)
 
1081
false
 
1082
> print(res)
 
1083
userdata: 0003D880
 
1084
> print(res.code,res.msg)
 
1085
42      Hosed
 
1086
>
 
1087
</pre></div>
 
1088
 
 
1089
<p>
 
1090
Note: is is also possible (though tedious) to have a function throw several different kinds of exceptions. To process this
 
1091
will require a pcall, followed by a set of if statements checking the type of the error.
 
1092
</p>
 
1093
<p>
 
1094
All of this code assumes that your C++ code uses exception specification (which a lot doesn't).
 
1095
If it doesn't consult the "<a href="SWIGPlus.html#SWIGPlus_catches">Exception handling with %catches</a>" section
 
1096
and the "<a href="Customization.html#exception">Exception handling with %exception</a>" section, for more details on how to
 
1097
add exception specification to functions or globally (respectively).
 
1098
</p>
 
1099
 
 
1100
 
 
1101
<H3><a name="Lua_nn23"></a>22.3.16 Writing your own custom wrappers</H3>
 
1102
 
 
1103
 
 
1104
<p>
 
1105
Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native Lua API calls. These 'native' functions allow direct adding of your own code into the module. This is performed with the <tt>%native</tt> directive as follows:
 
1106
</p>
 
1107
<div class="code"><pre>%native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
959
1108
...
960
1109
%{
961
1110
int native_function(lua_State*L) // my native code
968
1117
The <tt>%native</tt> directive in the above example, tells SWIG that there is a function <tt>int native_function(lua_State*L);</tt> which is to be added into the module under the name '<tt>my_func</tt>'. SWIG will not add any wrappering for this function, beyond adding it into the function table. How you write your code is entirely up to you.
969
1118
</p>
970
1119
 
971
 
<H2><a name="Lua_nn23"></a>22.4 Details on the Lua binding</H2>
 
1120
<H3><a name="Lua_nn24"></a>22.3.17 Adding additional Lua code</H3>
 
1121
 
 
1122
 
 
1123
<p>
 
1124
As well as adding additional C/C++ code, its also possible to add your own Lua code to the module as well.
 
1125
This code is executed once all other initialisation, including the %init code has been called.
 
1126
</p>
 
1127
<p>
 
1128
The directive <tt>%luacode</tt> adds code into the module which is executed upon loading. Normally you would
 
1129
use this to add your own functions to the module. Though you could easily perform other tasks.
 
1130
</p>
 
1131
<div class="code"><pre>%module example;
 
1132
 
 
1133
%luacode {
 
1134
  function example.greet() 
 
1135
    print "hello world" 
 
1136
  end
 
1137
 
 
1138
  print "Module loaded ok"
 
1139
}
 
1140
...
 
1141
%}
 
1142
</pre></div>
 
1143
<p>
 
1144
Notice that the code is not part of the module table. Therefore any references to the module must have the 
 
1145
module name added.
 
1146
</p>
 
1147
<p>
 
1148
Should there be an error in the Lua code, this will <em>not</em> stop loading of the module.
 
1149
The default behaviour of SWIG is to print a error message to stderr and then continue. 
 
1150
It is possible to change this behaviour by using a <tt>#define SWIG_DOSTRING_FAIL(STR)</tt> to
 
1151
define a different behaviour should the code fail.
 
1152
</p>
 
1153
<p>
 
1154
Good uses for this feature is adding of new code, or writing helper functions to simplify some of the code.
 
1155
See Examples/lua/arrays for an example of this code.
 
1156
</p>
 
1157
 
 
1158
<H2><a name="Lua_nn25"></a>22.4 Details on the Lua binding</H2>
972
1159
 
973
1160
 
974
1161
<p>
979
1166
 </i>
980
1167
</p>
981
1168
 
982
 
<H3><a name="Lua_nn24"></a>22.4.1 Binding global data into the module.</H3>
 
1169
<H3><a name="Lua_nn26"></a>22.4.1 Binding global data into the module.</H3>
983
1170
 
984
1171
 
985
1172
<p>
995
1182
double Foo_get();
996
1183
</pre></div>
997
1184
<p>
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.
 
1185
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.
999
1186
</p>
1000
1187
<div class="targetlang"><pre>
1001
1188
&gt; print(example)
1039
1226
<p>
1040
1227
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)'.
1041
1228
</p>
1042
 
<H3><a name="Lua_nn25"></a>22.4.2 Userdata and Metatables</H3>
 
1229
<H3><a name="Lua_nn27"></a>22.4.2 Userdata and Metatables</H3>
1043
1230
 
1044
1231
 
1045
1232
<p>
1119
1306
<p>
1120
1307
Note: Operator overloads are basically done in the same way, by adding functions such as '__add' &amp; '__call' to the classes metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
1121
1308
</p>
1122
 
<H3><a name="Lua_nn26"></a>22.4.3 Memory management</H3>
 
1309
<H3><a name="Lua_nn28"></a>22.4.3 Memory management</H3>
1123
1310
 
1124
1311
 
1125
1312
<p>