-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathLua.html
1745 lines (1537 loc) · 67.9 KB
/
Lua.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SWIG and Lua</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body bgcolor="#ffffff">
<H1><a name="Lua"></a>26 SWIG and Lua</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>
<li><a href="#Lua_nn12">Pointers</a>
<li><a href="#Lua_nn13">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>
</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_nn27">Typemaps and arrays</a>
<li><a href="#Lua_nn28">Typemaps and pointer-pointer functions</a>
</ul>
<li><a href="#Lua_nn29">Writing typemaps</a>
<ul>
<li><a href="#Lua_nn30">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 ANSI C and C++). It's also a <em>really</em> tiny language, less than 6000 lines of code, which compiles to <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"></a>26.1 Preliminaries</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 supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore.
</p>
<H2><a name="Lua_nn3"></a>26.2 Running SWIG</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"></a>26.2.1 Additional command line options</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="code"><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>
</table>
<H3><a name="Lua_nn4"></a>26.2.2 Compiling and Linking and Interpreter</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 <stdio.h>
#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<2)
{
printf("%s: <filename.lua>\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 & 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"></a>26.2.3 Compiling a dynamic module</H3>
<p>
Most, but not all platforms support the dynamic loading of modules (Windows & 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 -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -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"></a>26.2.4 Using your module</H3>
<p>
Assuming all goes well, you will be able to this:
</p>
<div class="targetlang"><pre>
$ ./my_lua
> print(example.gcd(4,6))
2
> print(example.Foo)
3
> example.Foo=4
> print(example.Foo)
4
>
</pre></div>
<H2><a name="Lua_nn7"></a>26.3 A tour of basic C/C++ wrapping</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"></a>26.3.1 Modules</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"></a>26.3.2 Functions</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>
> print example.fact(4)
24
>
</pre></div>
<p>
To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care.
</p>
<div class="targetlang"><pre>
> for k,v in pairs(example) do _G[k]=v end
> print(fact(4))
24
>
</pre></div>
<p>
It is also possible to rename the module with an assignment.
</p>
<div class="targetlang"><pre>
> e=example
> print(e.fact(4))
24
> print(example.fact(4))
24
</pre></div>
<H3><a name="Lua_nn10"></a>26.3.3 Global variables</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>
> print(example.Foo)
3
> c=example.Foo -- c is a COPY of example.Foo, not the same thing
> example.Foo=4
> print(c)
3
> c=5 -- this will not effect the original example.Foo
> 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>
> e=example
> -- e and example are the same table
> -- so e.Foo and example.Foo are the same thing
> example.Foo=4
> 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>
> print(e.Foo) -- reading works ok
4
> 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>
> -- example.PI does not exist
> print(example.PI)
nil
> example.PI=3.142 -- new value added
> 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>
> -- Applicable only with -eluac. (num is defined)
> print(example.num_get())
20
> example.num_set(50) -- new value added
> 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"></a>26.3.4 Constants and enums</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>
> print(example.ICONST)
10
> print(example.const.SUNDAY)
0
> print(example.const.SCONST)
Hello World
</pre></div>
<H3><a name="Lua_nn12"></a>26.3.5 Pointers</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 <file.h> 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>
> f=example.fopen("junk","w")
> example.fputs("Hello World",f)
> 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>
> print(f)
userdata: 003FDA80
> 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 & 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>
> f=example.fopen("not there","r") -- this will return a NULL in C
> print(f)
nil
</pre></div>
<H3><a name="Lua_nn13"></a>26.3.6 Structures</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>
> p=example.new_Point()
> p.x=3
> p.y=5
> print(p.x,p.y)
3 5
>
</pre></div>
<p>
Similar access is provided for unions and the data members of C++ classes.<br>
C structures are created using a function <tt>new_Point()</tt>, but for C++ classes are 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>
> 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>
> b = Bar()
> 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 = &b->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>
> b = Bar()
> b.f.a = 3 -- Modify attribute of structure member
> x = b.f
> 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;
};
> --From eLua
> a = example.new_data()
> example.data_x_set(a, 10)
> example.data_y_set(a, 20)
> 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"></a>26.3.7 C++ classes</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>
> l = example.List()
> l:insert("Ale")
> l:insert("Stout")
> l:insert("Lager")
> print(l:get(1))
Stout
> print(l:length)
3
>
</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="targetlang"><pre>class Spam {
public:
static void foo();
static int bar;
};
</pre></div>
<p>
In Lua, the static members can be accessed as follows:
</p>
<div class="code"><pre>
> example.Spam_foo() -- calling Spam::foo()
> a=example.Spam_bar -- reading Spam::bar
> 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>
> s=example.Spam() -- s is a Spam instance
> s.foo() -- Spam::foo() via an instance
-- does NOT work
</pre></div>
<H3><a name="Lua_nn15"></a>26.3.8 C++ inheritance</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"></a>26.3.9 Pointers, references, values, and arrays</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 &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>
> f = Foo() -- Create a Foo
> spam1(f) -- Ok. Pointer
> spam2(f) -- Ok. Reference
> spam3(f) -- Ok. Value.
> 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 &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"></a>26.3.10 C++ overloaded functions</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>
> foo(3) -- foo(int)
> 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>
> 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 &);
...
};
</pre></div>
<p>
you can write Lua code like this:
</p>
<div class="targetlang"><pre>
> f = Foo() -- Create a Foo
> 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 &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"></a>26.3.11 C++ operators</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 &c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &operator=(const Complex &c);
Complex operator+(const Complex &c) const;
Complex operator-(const Complex &c) const;
Complex operator*(const Complex &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>
> c = Complex(3,4)
> d = Complex(7,8)
> e = c + d
> e:re()
10.0
> 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="targetlang"><pre>class Complex {
...
friend Complex operator+(double, const Complex &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="targetlang"><pre>%rename(Complex_add_dc) operator+(double, const Complex &);
...
Complex operator+(double, const Complex &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>__neg__</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 (SWIG maps C++'s <tt>~</tt> to Lua's <tt>..</tt>)
<li><tt>__eq__</tt> operator<tt>==</tt>
<li><tt>__lt__</tt> operator<tt><</tt>
<li><tt>__le__</tt> operator<tt><=</tt>
</ul>
<p>
Note: in Lua, only the equals, less than, and less than equals operators are defined. The other operators (!=,>,>=) 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->re(),this->im());
return buffer;
}
</pre></div>
<p>
Then this will support the following code in Lua
</p>
<div class="targetlang"><pre>
> c = Complex(3,4)
> d = Complex(7,8)
> e = c + d
> print(e)
Complex(10,12)
> s=tostring(e) -- s is the number in string form
> 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>
<H3><a name="Lua_nn19"></a>26.3.12 Class extension with %extend</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 &c) : rpart(c.rpart), ipart(c.ipart) { }
Complex &operator=(const Complex &c);
Complex operator+(const Complex &c) const;
Complex operator-(const Complex &c) const;
Complex operator*(const Complex &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->re(),$self->im());
return tmp;
}
bool operator==(const Complex& c)
{ return ($self->re()==c.re() && $self->im()==c.im();}
};
</pre></div>
<p>
Now, in Lua
</p>
<div class="targetlang"><pre>
> c = Complex(3,4)
> d = Complex(7,8)
> e = c + d
> print(e) -- print uses __str__ to get the string form to print
Complex(10,12)
> print(e==Complex(10,12)) -- testing the == operator
true
> print(e!=Complex(12,12)) -- the != uses the == operator
true
</pre></div>