*** empty log message ***
[luabind.git] / doc / docs.html
blobbe757c1d33fc78a6d3f5b73672d4303d06280194
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
3 <html>
4 <head>
5 <title>luabind beta documentation</title>
6 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
7 <link href="style.css" type="text/css" rel="stylesheet">
8 </head>
10 <body>
12 <p>This library is currently in public beta phase. This documentation should be considered beta as well.
13 Please report any grammatical corrections/spelling corrections.</p>
15 <h1>Table of contents</h1>
17 <ol>
18 <li><a href="#intro">Introduction</a>
19 <ul>
20 <li><a href="#features">features</a>
21 <li><a href="#compilers">tested compilers</a>
22 </ul>
23 <li><a href="#build">Building luabind</a>
24 <li><a href="#basic">Basic usage</a>
25 <li><a href="#scopes">Scopes</a>
26 <li><a href="#fun">Binding functions to lua</a>
27 <ul>
28 <li><a href="#fun_overload">overloaded functions</a>
29 <li><a href="#fun_sigmatch">signature matching</a>
30 <li><a href="#lua_fun">calling lua functions</a>
31 </ul>
32 <li><a href="#bind_classes">Binding classes to lua</a>
33 <ul>
34 <li><a href="#class_property">properties</a>
35 <li><a href="#class_enum">enums</a>
36 <li><a href="#class_operator">operators</a>
37 <li><a href="#class_derived">derived classes</a>
38 <li><a href="#class_smart_pointers">smart_pointers</a>
39 </ul>
40 <li><a href="#object">Object</a>
41 <ul>
42 <li><a href="#object_iterators">iterators</a>
43 <li><a href="#object_functions">related functions</a>
44 <li><a href="#functor">functor</a>
45 </ul>
46 <li><a href="#class_lua" >Defining classes in lua</a>
47 <ul>
48 <li><a href="#class_lua_derive">deriving in lua</a>
49 <li><a href="#class_lua_operators">overloading operators</a>
50 <li><a href="#class_lua_finalizers">finalizers</a>
51 </ul>
52 <li><a href="#exceptions">Exceptions</a>
53 <li><a href="#policies" >Parameter policies</a>
54 <ul>
55 <li><a href="#policies_copy">copy</a>
56 <li><a href="#policies_adopt">adopt</a>
57 <li><a href="#policies_dependency">dependency</a>
58 <li><a href="#policies_return_ref">return_reference_to</a>
59 <li><a href="#policies_out">out_value</a>
60 <li><a href="#policies_pure_out">pure_out_value</a>
61 <li><a href="#policies_discard_result">discard_result</a>
62 <li><a href="#policies_return_stl_iterator">return_stl_iterator</a>
63 <li><a href="#policies_yield">yield</a>
64 <li><a href="#policies_custom">custom</a>
65 <li><a href="#policies_user_converter">user defined converter</a>
66 </ul>
67 <li><a href="#examples">Examples</a>
68 <ul>
69 <li><a href="#examples_cln">Class Library for Numbers</a>
70 </ul>
71 <li><a href="#config">Configuration</a>
72 <li><a href="#implementation_notes">Implementation notes</a>
73 <li><a href="#error_messages">Error messages</a>
74 <li><a href="#faq">FAQ</a>
75 <li><a href="#future">Future additions</a>
76 <li><a href="#issues">Known issues</a>
77 <li><a href="#acknowledgments">Acknowledgments</a>
78 </ol>
80 <h1><a name="intro"></a>Introduction</h1>
82 <p>Luabind is a library that helps you create bindings
83 between C++ and <a href="http://www.lua.org">lua</a>. It
84 has the ability to expose functions and classes, written in C++, to lua. It will
85 also supply the functionality to define classes in lua and let them derive from
86 other lua classes or C++ classes. Lua classes can override virtual functions
87 from their C++ base classes. It is written towards lua 5.0, and does not work
88 with lua 4.</p>
90 <p>It is implemented utilizing template meta programming.
91 That means that you don't need an extra preprocess pass to compile your project
92 (it is done by the compiler). It also means you don't (usually) have to know the
93 exact signature of each function you register, since the library will generate
94 code depending on the compile-time type of the function (which includes the
95 signature). The main drawback of this approach is that the compilation time will
96 increase for the file that does the registration, it is therefore recommended
97 that you register everything in the same cpp-file.</p>
99 <p>luabind is released under the terms of the
100 <a href="http://www.opensource.org/licenses/mit-license.php">MIT license</a>.</p>
102 <p>We are very interested in hearing about projects that use luabind, please let
103 us know about your project.</p>
105 <h2><a name="features"></a>features</h2>
107 <p>Luabind supports:</p>
108 <ul>
109 <li>overloaded free functions
110 <li>C++ classes in lua
111 <ul>
112 <li>overloaded member functions
113 <li>operators
114 <li>properties
115 <li>enums
116 </ul>
117 <li>lua functions in C++
118 <li>lua classes in C++
119 <li>lua classes (single inheritance)
120 <ul>
121 <li>derives from lua or C++ classes
122 <li>override virtual functions from C++ classes
123 </ul>
124 <li>implicit casts between registered types
125 <li>best match signature matching
126 <li>return value policies and parameter policies
127 </ul>
129 <h2><a name="compilers"></a>tested compilers</h2>
131 <p>Luabind has been tested to work on the following
132 compilers:</p>
134 <ul>
135 <li>Visual Studio 7.1
136 <li>Visual Studio 7.0
137 <li>Visual Studio 6.0 (sp 5)
138 <li>Intel C++ 6.0 (Windows)
139 <li>GCC 2.95.3 (cygwin)
140 <li>GCC 3.0.4 (Debian/Linux)
141 <li>GCC 3.1 (SunOS 5.8)
142 <li>GCC 3.2 (cygwin)
143 </ul>
145 <p>It has been confirmed not to work with:</p>
147 <ul>
148 <li>GCC 2.95.2 (SunOS 5.8)
149 </ul>
151 <p>Metrowerks 8.3 (Windows) compiles but fails the const-test. This means that const member
152 functions are treated as non-const member functions.</p>
154 <p>If you have tried luabind with a compiler not listed here, let us know
155 your result with it.</p>
157 <h1><a name="build"></a>Building luabind</h1>
159 <p>To keep down the compilation-time luabind is built as a library. This means you
160 have to either build it and lika against it, or include its source files in your project.
161 You also have to make sure the <tt>luabind</tt> directory is somewhere in your compiler's
162 include path. It requires <a href="http://www.boost.org">boost</a> 1.30.0 to be installed
163 (only boost headers). It also requires that lua is installed.</p>
165 <p>There is a makefile in the root-directory that will build the library and the test program.
166 If you are using a UNIX-system (or cygwin) they will make it easy to build luabind as a static
167 library. If you are using Visual Studio it may be easier to include the files in the <tt>src</tt>
168 directory in your project.</p>
170 <p>When building luabind you have several options that may streamline the library to better suit
171 your needs. It is extremely important that your application has the same settings as the library
172 was built with. The available options are found in the <a href="#config">Configuration</a> section.</p>
174 <p>If you want to change the settings to differ from the default, it's recommended that you define
175 the settings on the commandline of all your files (in the project settings in visual studio).</p>
177 <h1><a name="basic"></a>Basic usage</h1>
179 <p>To use luabind, you must include <tt>lua.h</tt> and luabind's main header file.</p>
181 <pre>
182 extern "C"
184 #include "lua.h"
187 #include &lt;luabind/luabind.hpp&gt;
188 </pre>
190 <p>This includes support for both registering classes and functions. If you just want to
191 have support for functions or classes you can include <tt>&lt;luabind/function.hpp&gt;</tt>
192 and <tt>&lt;luabind/class.hpp&gt;</tt> separately.</p>
194 <pre>
195 #include &lt;luabind/function.hpp&gt;
196 #include &lt;luabind/class.hpp&gt;
197 </pre>
199 <p>The first thing you need to do is to call <tt>luabind::open(lua_State*)</tt> which will
200 register the functions to create classes from lua, and initialize some state-global
201 structures used by luabind. If you don't call this function you will hit asserts later in
202 the library. There is no corresponding close function because once a class has been registered
203 in lua, there really isn't any good way to remove it. Partly because any remaining instances
204 of that class relies on the class being there. Everything will be cleaned up when the state
205 is closed though.</p>
207 <p>Note that no luabind header will include <tt>"lua.h"</tt>, this is up to you. You have to include
208 it before any luabind header is included.</p>
211 <h1><a name="scopes"></a>Scopes</h1>
213 <p>Everything that gets registered in lua is registered in a namespace (lua tables) or in the global
214 scope (called module). All registrations must be surrounded by its scope. To define a module, the
215 <tt>luabind::module</tt> class is used. It is used like this:</p>
217 <pre>
218 module(L)
220 // declarations
222 </pre>
224 <p>This will register all declared functions or classes in the global namespace in lua. If you want
225 to have a namespace for your module (like the standard libraries) you can give a name to the constructor,
226 like this:</p>
228 <pre>
229 module(L, "my_library")
231 // declarations
233 </pre>
235 <p>Here all declarations will be put in the <tt>my_library</tt> table.</p>
237 <p>If you want nested namespaces you can use the <tt>luabind::namespace_</tt> class. It works exactly
238 as <tt>luabind::module</tt> except that it doesn't take a <tt>lua_State*</tt> in it's constructor.
239 An example of its usage could look like this:</p>
241 <pre>
242 module(L, "my_library")
245 // declarations
247 namespace_("detail")
249 // library-private declarations
253 </pre>
255 <p>As you might have figured out, the following declarations are equivalent:</p>
257 <pre>
258 module(L)
260 namespace_("my_library")
262 // declarations
266 </pre>
268 <pre>
269 module(L, "my_library")
271 // declarations
273 </pre>
275 <p>Each declaration must be separated by a comma, like this:</p>
277 <pre>
278 module(L)
280 def("f", &amp;f),
281 def("g", &amp;g),
282 class_&lt;A&gt;("A")
283 .def(construcor&lt;int, int&gt;),
284 def("h", &amp;h)
286 </pre>
288 <p>More about the actual declarations in the <a href="#fun">Binding functions to lua</a> and
289 <a href="#bind_classes" >Binding classes to lua</a> sections.</p>
291 <p>A word of caution, if you are in <b>really</b> bad need for performance, putting your functions
292 in tables will increase the lookup time.</p>
294 <h1><a name="fun"></a>Binding functions to lua</h1>
296 <p>To bind functions to lua you use the function <tt>luabind::def()</tt>. It has the following
297 synopsis:</p>
299 <pre>
300 template&lt;class F, class policies&gt;
301 void def(const char* name, F f, const Policies&amp;);
302 </pre>
304 <ul>
305 <li>name is the name the function will have within lua.
306 <li>F is the function pointer you want to register.
307 <li>The Policies parameter is used to describe how
308 parameters and return values are treated by the function, this is an optional
309 parameter. More on this in <a href="#policies" >parameter policies</a>.
310 </ul>
312 <p>An example usage could be if you want to register the
313 function <tt>float std::sin(float)</tt>:</p>
315 <pre>
316 module(L)
318 def("sin", &amp;std::sin)
320 </pre>
322 <h2><a name="fun_overload"></a>overloaded functions</h2>
324 <p>If you have more than one function with the same name,
325 and want to register them in lua, you have to explicitly give the signature.
326 This is to let C++ know which function you refer to. For example, if you have
327 two functions, <tt>int&nbsp;f(const&nbsp;char*)</tt> and <tt>void&nbsp;f(int)</tt>.</p>
329 <pre>
330 module(L)
332 def("f", (int(*)(const char*)) &amp;f),
333 def("f", (void(*)(int)) &amp;f)
335 </pre>
337 <h2><a name="fun_sigmatch"></a>signature matching</h2>
339 <p>luabind will generate code that checks the lua stack to
340 see if the values there can match your functions' signatures. It will handle
341 implicit typecasts between derived classes, and it will prefer matches with the
342 least number of implicit casts. In a function call, if the function is
343 overloaded and there's no overload that match the parameters better than the
344 other, you have an ambiguity. This will spawn a run-time error, stating that the
345 function call is ambiguous. A simple example of this is to register one function
346 that takes an <tt>int</tt> and one that takes a <tt>float</tt>. Since lua don't distinguish between floats and
347 integers, both will always match.</p>
349 <p>Since all overloads are tested, it will always find the
350 best match (not the first match). This also means that it can handle situations
351 where the only difference in the signature is that one member function is const
352 and the other isn't. For example, if the following function and class is
353 registered:</p>
355 <pre>
356 struct A
358 void f();
359 void f() const;
362 const A* create_a();
364 struct B: A {};
365 struct C: B {};
367 void g(A*);
368 void g(B*);
369 </pre>
371 <p>(note that <tt>create_a()</tt> would need an <a href="#policies_adopt" >adopt return value policy</a>. How to register classes is
372 described in <a href="#bind_classes" >Binding classes to lua</a>).</p>
374 <p>And the following lua code is executed:</p>
376 <pre>
377 a1 = create_a()
378 a1:f() -- the const version is called
380 a2 = A()
381 a2:f() -- the non-const version is called
383 a = A()
384 b = B()
385 c = C()
387 g(a) -- calls g(A*)
388 g(b) -- calls g(B*)
389 g(c) -- calls g(B*)
390 </pre>
392 <h2><a name="lua_fun"></a>calling lua functions</h2>
394 <p>To call a lua function, you can either use <tt>call_function()</tt>, <tt>call_member()</tt>, an
395 <a href="#object"><tt>object</tt></a> or <a href="#functor"><tt>functor</tt></a>.</p>
397 <h3><tt>template&lt;class Ret&gt;<br>
398 Ret call_function(lua_State* L, const char* name, ...)</tt></h3>
399 <p>This calls the global function called <tt>name</tt>. This function can only call global lua functions. The
400 ... represents a variable number of parameters that are sent to the lua function. This function call may
401 throw <tt>luabind::error</tt> if the function call fails.</p>
403 <p>The return value isn't actually <tt>Ret</tt> (the template parameter), but a proxy object that will do
404 the function call. This enables you to give policies to the call. You do this with the operator[]. You
405 give the policies within the brackets, like this:</p>
407 <pre>
408 int ret = call_function&lt;int&gt;(L, "a_lua_function", new complex_class())[ adopt(_1) ];
409 </pre>
411 <h3><tt>template&lt;class Ret&gt;<br>
412 Ret call_member(object&amp;, const char* name, ...)</tt></h3>
413 <p>This treats the given <tt>object</tt> as an instance of a class. The given name is the name of a member
414 function to call. The ... represents a variable number of parameters given to the function. This function may
415 throw <tt>luabind::error</tt> if the function call fails.</p>
417 <p>You can give policies to a member function call the same way as you do with <tt>call_function</tt>.</p>
419 <h1><a name="bind_classes"></a>Binding classes to lua</h1>
421 <p>To register classes you use a class called <tt>class_</tt>. Its name is supposed to resemble the C++
422 keyword, to make it look more intuitive. It has an overloaded member function
423 <tt>def()</tt> that is used to register member functions,
424 operators, constructors, enums and properties on the class. It will return its
425 this-pointer, to let you register more members directly.</p>
427 <p>Let's start with a simple example. Consider the
428 following C++ class:</p>
430 <pre>
431 class testclass
433 public:
434 testclass(const std::string&amp; s): m_string(s) {}
435 void print_string() { std::cout &lt;&lt; m_string &lt;&lt; "\n"; }
436 private:
437 std::string m_string;
439 </pre>
441 <p>To register it with a lua environment, write as follows
442 (assuming you are <tt>using namespace luabind</tt>):</p>
444 <pre>
445 module(L)
447 class_&lt;testclass&gt;("testclass")
448 .def(constructor&lt;const std::string&amp;&gt;())
449 .def("print_string", &amp;testclass::print_string)
451 </pre>
453 <p>This will register the class with the name <tt>testclass</tt> and constructor that takes a string as
454 argument and one member function with the name <tt>print_string</tt>.</p>
456 <pre>
457 -- instantiate the class
458 a = testclass('a string')
460 -- call the member function print_string on it
461 -- this will print 'a string' on stdout
462 a:print_string()
463 </pre>
465 <p>It is also possible to register free functions as member
466 functions. The requirement on the function is that it takes a pointer, const
467 pointer, reference or const reference to the class type as the first parameter.
468 The rest of the parameters are the ones that are visible in lua, while the
469 object pointer is given as the first parameter. If we have the following C++
470 code:</p>
472 <pre>
473 struct A
475 int a;
478 int plus(A* o, int v) { return o-&gt;a + v; }
479 </pre>
481 <p>You can register the plus, function as if it was a
482 member function on <tt>A</tt> like this:</p>
484 <pre>
485 class_&lt;A&gt;("A")
486 .def("plus", &amp;plus)
487 </pre>
489 <p><tt>plus</tt> can now be called as
490 a member function on A with one parameter, <tt>int</tt>. If
491 the object pointer parameter is const, the function will act as if it was a
492 const member function (it can be called on const objects).</p>
494 <h2><a name="class_property"></a>properties</h2>
496 <p>To register a global data member with a class is easily
497 done. Consider the following class:</p>
499 <pre>
500 struct A
502 int a;
504 </pre>
506 <p>This class is registered like this:</p>
508 <pre>
509 module(L)
511 class_&lt;A&gt;("A")
512 .def_readwrite("a", &amp;A::a)
514 </pre>
516 <p>Then it's both readable and writable. You can
517 also register attributes as read-only.</p>
519 <pre>
520 module(L)
522 class_&lt;A&gt;("A")
523 .def_readonly("a", &amp;A::a)
525 </pre>
527 <p>You can also register getter and setter functions and
528 make them look as if they were a public data member. Consider the following
529 class:</p>
531 <pre>
532 class A
534 void set_a(int x) { a_ = x; }
535 int get_a() const { return a_; }
536 private:
537 int a_;
539 </pre>
541 <p>It can be registered as if it had a public data member
542 <tt>a</tt> like this:</p>
544 <pre>
545 class_&lt;A&gt;("A")
546 .property("a", &amp;A::get_a, &amp;A::set_a)
547 </pre>
549 <p>This way the <tt>get_a()</tt> and
550 <tt>set_a()</tt> functions will be called instead of just
551 writing to the data member. If you want to make it read only you can just omit
552 the last parameter.</p>
554 <h2><a name="class_enum"></a>enums</h2>
556 <p>If your class contains enumerated constants (enums), you
557 can register them as well to make them available in lua. Note that they will not
558 be type safe, all enums are integers in lua, and all functions that takes an
559 enum, will accept any integer. You register them like this:</p>
561 <pre>
562 module(L)
564 class_&lt;A&gt;("A")
565 .enum_("constants")
567 value("my_enum", 4),
568 value("my_2nd_enum", 7),
569 value("another_enum", 6)
572 </pre>
574 <p>In lua they are reached like any data member, except
575 that they are read-only and reached on the class itself rather than on an
576 instance of the class.</p>
578 <pre>
579 print(A.my_enum)
580 print(A.another_enum)
581 </pre>
583 <p>In this example the numbers 4 and 6 are printed.</p>
585 <h2><a name="class_operator"></a>operators</h2>
587 <p>The mechanism for registering operators on your class is
588 pretty simple. You use a global name <tt>luabind::self</tt>
589 to refer to the class itself and then you just write the operator expression
590 inside the <tt>def()</tt> call. This class:</p>
592 <pre>
593 struct vec
595 vec operator+(int s);
597 </pre>
599 <p>Is registered like this:</p>
601 <pre>
602 module(L)
604 class_&lt;vec&gt;("vec")
605 .def(self + int())
607 </pre>
609 <p>This will work regardless if your plus operator is
610 defined inside your class or as a free function.</p>
612 <p>If you operator is <tt>const</tt> (or, when defined as a free function,
613 takes a const reference to the class itself) you have to use <tt>const_self</tt>
614 instead of <tt>self</tt>. Like this:</p>
616 <pre>
617 module(L)
619 class_&lt;vec&gt;("vec")
620 .def(const_self + int())
622 </pre>
624 <p>The operators supported are those available in lua:</p>
626 <ul>
627 <li>+
628 <li>-
629 <li>*
630 <li>/
631 <li>^
632 <li>&lt;
633 <li>&lt;=
634 <li>==
635 <li>unary -
636 <li>operator()
637 </ul>
639 <p>This means, no in-place operators. The equality operator (==) has a little
640 hatch, it will not be called if the references are equal. This means that
641 the == operator has to do pretty much what's it's expected to do.</p>
643 <p>In the above example the other operand type is
644 instantiated by writing <tt>int()</tt>. If the operand type
645 is a complex type that cannot easily be instantiated you can wrap the type in a
646 class called <tt>other</tt>. For example:</p>
648 <p>To register this class, we don't want to instantiate a
649 string just to register the operator.</p>
651 <pre>
652 struct vec
654 vec operator+(std::string);
656 </pre>
658 <p>Instead we use the <tt>other</tt>
659 wrapper like this:</p>
661 <pre>
662 module(L)
664 class_&lt;vec&gt;("vec")
665 .def(self + other&lt;std::string&gt;())
667 </pre>
669 <p>To register an application operator:</p>
671 <pre>
672 module(L)
674 class_&lt;vec&gt;("vec")
675 .def( self(int()) )
677 </pre>
679 <p>There's one special operator. In lua it's called <tt>__tostring</tt>,
680 it's not really an operator. It is used for converting objects to strings
681 in a standard way in lua. If you register this functionality, you will
682 be able to use the lua standard function <tt>tostring()</tt> for converting
683 you object to a string.</p>
685 <p>To implement this operator in C++ you should supply an
686 operator<tt>&lt;&lt;</tt> for <tt>ostream</tt>. Like this example:</p>
688 <pre>
689 class number {};
691 std::ostream&amp; operator&lt;&lt;(ostream&amp;, number&amp;);
692 </pre>
694 <pre>
695 module(L)
697 class_&lt;number&gt;("number")
698 .def(tostring(self))
700 </pre>
703 <h2><a name="class_derived"></a>derived classes</h2>
705 <p>If you want to register classes that derives from other
706 classes, you can specify a template parameter <tt>bases&lt;&gt;</tt> to
707 the <tt>class_</tt> instantiation. The following hierarchy:</p>
709 <pre>
710 struct A {};
711 struct B: A{};
712 </pre>
714 <p>Would be registered like this:</p>
716 <pre>
717 module(L)
719 class_&lt;A&gt;("A"),
720 class_&lt;B, A&gt;("B")
722 </pre>
724 <p>If you have multiple inheritance you can specify more
725 than one base. If <tt>B</tt> would also derive from a class
726 <tt>C</tt>, it would be registered like this:</p>
728 <pre>
729 module(L)
731 class_&lt;B, bases&lt;A, C&gt; &gt;("B")
733 </pre>
735 <p>Note that you can omit <tt>bases&lt;..&gt;</tt> when using single inheritance.</p>
737 <p>If you don't specify that classes derive from each
738 other, luabind will not be able to implicitly cast pointers between the types.
739 If for example, you forget to tell that <tt>B</tt> derives
740 from <tt>A</tt> and we have a function with the following
741 signature:</p>
743 <pre>
744 void f(A*);
745 </pre>
747 <p>The following code will not run:</p>
749 <pre>
750 b = B()
751 f(b) -- error, no function 'f' matches the arguments (B)
752 </pre>
754 <p>Because luabind doesn't know that a <tt>B*</tt> can be cast to an <tt>A*</tt>.</p>
756 <h2><a name="class_smart_pointers"></a>smart_pointers</h2>
758 <p>When you register a class you can tell luabind that all instances of that class should be held
759 by some kind of smart pointer (<tt>boost::shared_ptr</tt> for instance). You do this by giving
760 the holder type as an extra template-parameter to the <tt>class_</tt> your constructing, like this:</p>
762 <pre>
763 module(L)
765 class_&lt;A, boost::shared_ptr&lt;A&gt; &gt;("A");
767 </pre>
769 <p>You also have to supply two functions for your smart pointer. One that returns the type of const
770 version of the smart pointer type (<tt>boost::shared_ptr&lt;const A&gt;</tt> in this case). And one
771 function that extracts the raw pointer from the smart pointer. The first function is needed because
772 luabind has to allow the non-const&nbsp;-&gt;&nbsp;conversion when passing values from lua to C++. The second
773 function is needed when lua calls member functions on held types, the this pointer must be a raw
774 pointer, it is also needed to allow the smart_pointer&nbsp;-&gt;&nbsp;raw_pointer conversion from
775 lua to C++. They look like this:</p>
777 <pre>
778 namespace luabind
780 template&lt;class T&gt;
781 T* get_pointer(boost::shared_ptr&lt;T&gt;&amp; p) { return p.get(); }
783 template&lt;class A&gt;
784 boost::shared_ptr&lt;const A&gt;* get_const_holder(boost::shared_ptr&lt;A&gt;*)
786 return 0;
789 </pre>
791 <p>The conversion that works are (given that B is a base class of A):</p>
793 <table>
794 <tr>
795 <td colspan="2"><h3>from lua to C++</h3></td>
796 </tr>
797 <tr>
798 <td>holder_type&lt;A&gt;</td>
799 <td>A*</td>
800 </tr>
801 <tr>
802 <td>holder_type&lt;A&gt;</td>
803 <td>B*</td>
804 </tr>
805 <tr>
806 <td>holder_type&lt;A&gt;</td>
807 <td>const A*</td>
808 </tr>
809 <tr>
810 <td>holder_type&lt;A&gt;</td>
811 <td>const B*</td>
812 </tr>
813 <tr>
814 <td>holder_type&lt;A&gt;</td>
815 <td>holder_type&lt;A&gt;</td>
816 </tr>
817 <tr>
818 <td>holder_type&lt;A&gt;</td>
819 <td>holder_type&lt;const A&gt;</td>
820 </tr>
821 <tr>
822 <td>holder_type&lt;const A&gt;</td>
823 <td>const A*</td>
824 </tr>
825 <tr>
826 <td>holder_type&lt;const A&gt;</td>
827 <td>const B*</td>
828 </tr>
829 <tr>
830 <td>holder_type&lt;const A&gt;</td>
831 <td>holder_type&lt;const A&gt;</td>
832 </tr>
833 <tr>
834 <td colspan="2"><h3>from C++ to lua</h3></td>
835 </tr>
836 <tr>
837 <td>holder_type&lt;A&gt;</td>
838 <td>holder_type&lt;A&gt;</td>
839 </tr>
840 <tr>
841 <td>holder_type&lt;const A&gt;</td>
842 <td>holder_type&lt;const A&gt;</td>
843 </tr>
844 <tr>
845 <td>const holder_type&lt;A&gt;&amp;</td>
846 <td>holder_type&lt;A&gt;</td>
847 </tr>
848 <tr>
849 <td>const holder_type&lt;const A&gt;&amp;</td>
850 <td>holder_type&lt;const A&gt;</td>
851 </tr>
853 </table>
855 <p>When using a holder type, it can be useful to know if the pointer is valid. For example when using
856 std::auto_ptr, the holder will be invalidated when passed as a parameter to a function.
857 For this purpose there is a member of all object instances in luabind: <tt>__ok</tt>.<p>
859 <pre>
861 struct test {};
862 void f(std::auto_ptr&lt;test&gt;);
864 module(L)
866 class_&lt;test&gt;("test")
867 .def(constructor&lt;&gt;()),
869 def("f", &amp;f)
872 a = test()
873 f(a)
874 print a.__ok -- prints false
876 </pre>
878 <h1><a name="object"></a>Object</h1>
880 <p>Since functions have to be able to take lua values (of variable type) we need a wrapper
881 around them. This wrapper is called <tt>luabind::object</tt>. If the function you register
882 takes an <tt>object</tt>, it will match any lua value. To use it, you need to include
883 <tt>&lt;luabind/object.hpp&gt;</tt>. The <tt>object</tt> class has the following synopsis:</p>
885 <pre>
886 class object
888 public:
889 class iterator;
890 class raw_iterator;
891 class array_iterator;
893 template&lt;class T&gt;
894 object(lua_State*, const T&amp; value);
895 object(const object&amp;);
896 object(lua_State*);
897 object();
899 ~object();
901 iterator begin() const;
902 iterator end() const;
903 raw_iterator raw_begin() const;
904 raw_iterator raw_end() const;
905 array_iterator abegin() const;
906 array_iterator aend() const;
908 void set();
909 lua_State* lua_state() const;
910 void pushvalue() const;
911 bool is_valid() const;
912 operator bool() const;
914 template&lt;class Key&gt;
915 <i>&lt;implementation-defined&gt;</i> operator[](const Key&amp;);
917 template&lt;class Key&gt;
918 object at(const Key&amp;) const;
920 template&lt;class Key&gt;
921 object raw_at(const Key&amp;) const;
923 template&lt;class T&gt;
924 object&amp; operator=(const T&amp;);
925 object&amp; operator=(const object&amp;);
927 template&lt;class T&gt;
928 bool operator==(const T&amp;) const;
929 bool operator==(const object&amp;) const;
930 bool operator&lt;(const object&amp;) const;
931 bool operator&lt;=(const object&amp;) const;
932 bool operator&gt;(const object&amp;) const;
933 bool operator&gt;=(const object&amp;) const;
934 bool operator!=(const object&amp;) const;
936 void swap(object&amp;);
937 int type() const;
939 <i>&lt;implementation-defined&gt;</i> operator()();
941 template&lt;class A0&gt;
942 <i>&lt;implementation-defined&gt;</i> operator()(const A0&amp; a0);
944 template&lt;class A0, class A1&gt;
945 <i>&lt;implementation-defined&gt;</i> operator()(const A0&amp; a0, const A1&amp; a1);
947 /* ... */
950 </pre>
952 <p>When you have a lua object, you can assign it a new value with the assignment operator (=). When
953 you do this, the <tt>default_policy</tt> will be used to make the conversion from C++ value to lua.
954 If your <tt>luabind::object</tt> is a table you can access its members through the operator[] or
955 the iterators. The value returned from the operator[] is a proxy object that can be used both
956 for reading and writing values into the table (using operator=). Note that it is impossible
957 to know if a lua value is indexable or not (lua_gettable doesn't fail, it succeeds or crashes).
958 This means that if you're trying to index something that cannot be indexed, you're on your own. Lua
959 will call its <tt>panic()</tt> function (you can define your own panic function using
960 <tt>lua_setpanicf</tt>). The <tt>at()</tt> and <tt>raw_at()</tt> functions returns the value
961 at the given table position (like operator[] but only for reading).<p>
963 <p>The ordinary <tt>object::iterator</tt> uses <tt>lua_gettable</tt> to extract the values from
964 the table, the standard way that will invoke metamethods if any. The <tt>object::raw_iterator</tt>
965 uses <tt>lua_rawget</tt> and <tt>object::array_iterator</tt> uses <tt>lua_rawgeti</tt>. The latter
966 will only iterate over numberical keys starting at 1 and continue until the first nil value.</p>
968 <p>The <tt>lua_state()</tt> function returns the lua state where this object is stored. If you want
969 to manipulate the object with lua functions directly you can push it onto the lua stack by calling
970 <tt>pushvalue()</tt>. And set the object's value by calling <tt>set()</tt>, which will pop the top
971 value from the lua stack and assign it to the object.</p>
973 <p>The operator== will run <tt>lua_equal()</tt>
974 on the operands and return its result.</p>
976 <p>The <tt>int type()</tt> member function will return the lua type of the object. It will return
977 the same values as <tt>lua_type()</tt>.</p>
979 <p>The <tt>is_valid</tt> function tells you whether the object has been initialized or not. When created
980 with its default constructor, objects are invalid. To make an object valid, you can assign it a value. If
981 you want to invalidate an object you can simply assign it an invalid object.</p>
983 <p>The <tt>operator bool()</tt>
984 isn't really an implicit cast to bool, but an implicit cast to a member pointer, since member pointers
985 don't have any arithmetic operators on them (which can cause hard to find errors). The functionality of
986 the cast-operator is equivalent to <tt>is_valid()</tt>. This means that:</p>
988 <pre>
989 object o;
990 // ...
991 if (o.is_valid())
993 // ...
995 </pre>
997 <p>is equivalent to:</p>
999 <pre>
1000 object o;
1001 // ...
1002 if (o)
1004 // ...
1006 </pre>
1008 <p>The application operator will call the value as if it was a function. You can give it any number
1009 of parameters (currently the <tt>default_policy</tt> will be used for the conversion). The returned
1010 object refers to the return value (currently only one return value is supported). This operator may
1011 throw <tt>luabind::error</tt> if the function call fails. If you want to specify
1012 <a href="#policies">policies</a> to your function call, you can use index-operator (operator[]) on
1013 the function call, and give the policies within the [ and ]. Like this:</p>
1015 <pre>
1016 my_function_object(2, 8, new my_complex_structure(6)) [ adopt(_3) ];
1017 </pre>
1019 <p>This tells luabind to make lua adopt the ownership and responsibility for the pointer passed in
1020 to the lua-function.</p>
1022 <p>It's important that all instances of <tt>object</tt> have been destructed by the time the lua state
1023 is closed. The object will keep a pointer to the lua state and release its lua object in its
1024 destructor.</p>
1026 <p>Here's an example of how a function can use a table.</p>
1028 <pre>
1029 void my_function(const object&amp; table)
1031 if (table.type() == LUA_TTABLE)
1033 table["time"] = std::clock();
1034 table["name"] = std::rand() &lt; 500 ? "unusual" : "usual";
1036 std::cout &lt;&lt; object_cast&lt;std::string&gt;(table[5]) &lt;&lt; "\n";
1039 </pre>
1041 <p>If you take a <tt>luabind::object</tt> as a parameter to a function, any lua value will match that parameter.
1042 That's why we have to make sure it's a table before we index into it.</p>
1044 <h2><a name="object_iterators"></a>iterators</h2>
1046 <p>The iterators, that are returned by the <tt>begin()</tt> and <tt>end()</tt> (and their variants) are (almost)
1047 models of the <a href="http://www.sgi.com/tech/stl/ForwardIterator.html">
1048 ForwardIterator</a> concept. The exceptions are that operator-&gt; and post increment doesn't exist on
1049 them.</p>
1051 <p>They look like this:</p>
1053 <pre>
1054 class object::iterator
1056 iterator();
1057 iterator(const iterator&amp;);
1059 iterator&amp; operator++();
1060 bool operator!=(const iterator&amp;) const;
1061 iterator&amp; operator=(const iterator&amp;);
1063 object key() const;
1065 <i>implementation-defined</i> operator*();
1067 </pre>
1069 <p>The implementation defined return value from the dereference operator is a proxy object that can be used as if it was
1070 an <tt>object</tt>, it can also be used to assign the specific table entry with a new value. If you want to assign a
1071 value to an entry pointed to by an iterator, just use the assignment operator on the dereferenced iterator:</p>
1073 <pre>
1074 *iter = 5;
1075 </pre>
1077 <p>The <tt>key()</tt> member returns the key used by the iterator when indexing the associated lua table.</p>
1079 <h2><a name="object_functions"></a>related functions</h2>
1082 There are a couple of functions related to objects and tables.
1083 </p>
1085 <h3><tt>T object_cast&lt;<i>Type</i>&gt;(const&nbsp;object&amp;);</tt><br>
1086 <tt>T object_cast&lt;<i>Type</i>&gt;(const&nbsp;object&amp;, const&nbsp;Policies&amp;);</tt><br>
1087 <tt>boost::optional&lt;T&gt; object_cast_nothrow&lt;<i>Type</i>&gt;(const&nbsp;object&amp;);</tt><br>
1088 <tt>boost::optional&lt;T&gt; object_cast_nothrow&lt;<i>Type</i>&gt;(const&nbsp;object&amp;, const&nbsp;Policies&amp;);</tt></h3>
1089 <p>The <tt>object_cast</tt> function casts the value of an <tt>object</tt> to a C++ value. You
1090 can supply a policy to handle the conversion from lua to C++. If the cast cannot be made a
1091 <tt>cast_failed</tt> exception will be thrown. If you have defined <tt>LUABIND_NO_ERROR_CHECKING</tt>
1092 (see <a href="#config">configuration</a>) no checking will occur, and if the cast is invalid the
1093 application may very well crash. The nothrow versions will return an uninitialized <tt>boost::optional&lt;T&gt;</tt>
1094 object, to indicate that the cast could not be performed.</p>
1096 <h3><tt>object get_globals(lua_State*);</tt><br>
1097 <tt>object get_registry(lua_State*);</tt></h3>
1098 <p>These functions return the global environment table and the registry table respectively.</p>
1100 <h3><tt>object newtable(lua_State*);</tt></h3>
1101 <p>This function creates a new table and returns an object to it.</p>
1103 <h2><a name="functor"></a>functor</h2>
1105 <p>The <tt>functor</tt> class is similar to <tt>object</tt>, with the exception that it can
1106 only be used to store functions. If you take it as a parameter, it will only match functions.</p>
1108 <p>To use it you need to include its header:</p>
1110 <pre>
1111 #include &lt;luabind/functor.hpp&gt;
1112 </pre>
1114 <p>It takes one template parameter, the return value of the lua function it represents.
1115 Currently the functor can have at most one return value (unlike lua functions). It has the
1116 following synopsis:</p>
1118 <pre>
1119 template&lt;class Ret&gt;
1120 class functor
1122 public:
1124 functor(lua_State*, const char* name);
1125 functor(const functor&amp;);
1127 ~functor();
1129 bool is_valid() const;
1130 operator bool() const;
1132 lua_State* lua_state() const;
1133 void pushvalue() const;
1135 bool operator==(const functor&lt;Ret&gt;&amp;);
1136 bool operator!=(const functor&lt;Ret&gt;&amp;);
1138 <i>&lt;implementation-defined&gt;</i> operator()() const;
1140 template&lt;class A0&gt;
1141 <i>&lt;implementation-defined&gt;</i> operator()(const A0&amp;) const;
1143 template&lt;class A0, class A1&gt;
1144 <i>&lt;implementation-defined&gt;</i> operator()(const A0&amp;, const A1&amp;) const;
1146 /* ... */
1148 </pre>
1150 <p>The application operator takes any parameters. The parameters are converted into lua and the
1151 function is called. The return value will act as if it was the type <tt>Ret</tt>, with the exception that you can use the
1152 return value to give policies to the call. You do this the same way as you do with <a href="#object">objects</a>,
1153 using the operator[], and giving the policies inside the brackets.</p>
1155 <p>The <tt>is_valid()</tt> function works just like the one on <a href="#object"><tt>object</tt></a>, it tells you if
1156 the functor has been assigned with a valid lua function. The <tt>operator bool()</tt> is an alias for this member function
1157 and also works just as the one found in <a href="#object"><tt>object</tt></a>.</p>
1159 <p>For example, if you have the following lua function:</p>
1161 <pre>
1162 function f(a, b)
1163 return a + b
1165 </pre>
1167 <p>You can expose it to C++ like this:</p>
1169 <pre>
1170 functor&lt;int&gt; f(L, "f");
1172 std::cout &lt;&lt; f(3, 5) &lt;&lt; "\n";
1173 </pre>
1175 <p>This will print out the sum of 3 and 5. Note that you can pass any parameters to the
1176 application operator of <a href="#functor"><tt>luabind::functor</tt></a>, this is because lua doesn't have
1177 signatures for its functions. All lua functions take any number of parameters
1178 of any type.</p>
1180 <p>If we have a C++ function that takes a <a href="#functor"><tt>luabind::functor</tt></a> and registers it, it will accept lua
1181 functions passed to it. This enables us to expose APIs that requires you to
1182 register callbacks. For example, if your C++ API looks like this:</p>
1184 <pre>
1185 void set_callback(void(*)(int, int));
1186 </pre>
1188 <pre>
1189 object o;
1190 // ...
1191 if (o.is_valid())
1193 // ...
1195 </pre>
1198 <p>And you want to expose it to lua, you have to wrap the
1199 call to the lua function inside a real C++ function, like this:</p>
1201 <pre>
1202 functor&lt;void&gt; lua_callback;
1204 void callback_wrapper(int a, int b)
1206 lua_callback(a, b);
1209 void set_callback_wrapper(const functor&lt;void&gt;&amp; f)
1211 lua_callback = f;
1212 set_callback(&amp;callback_wrapper);
1214 </pre>
1216 <p>And then register <tt>set_callback_wrapper</tt> instead of registering <tt>set_callback</tt>.
1217 This will have the effect that when one tries to register the callback from lua, your
1218 <tt>set_callback_wrapper</tt> will be called instead and first set the lua functor to the given function.
1219 It will then call the real <tt>set_callback</tt> with the <tt>callback_wrapper</tt>. The
1220 <tt>callback_wrapper</tt> will be called whenever the callback should be called, and it will simply
1221 call the lua function that we registered.</p>
1223 <p>You can also use <a href="#object_functions"><tt>object_cast</tt></a> to cast an object to a <a href="#functor"><tt>functor</tt></a>.</p>
1225 <h1><a name="class_lua"></a>Defining classes in lua</h1>
1227 <p>In addition to binding C++ functions and classes with
1228 lua, luabind also provide an oo-system in lua.</p>
1230 <pre>
1231 class 'lua_testclass'
1233 function lua_testclass:__init(name)
1234 self.name = name
1237 function lua_testclass:print()
1238 print(self.name)
1241 a = lua_testclass('example')
1242 a:print()
1243 </pre>
1245 <p>Inheritance can be used between lua-classes:</p>
1247 <pre>
1248 class 'derived' (lua_testclass)
1250 function derived:__init() super('derived name')
1253 function derived:print()
1254 print('Derived:print() -&gt; ')
1255 lua_testclass.print(self)
1257 </pre>
1259 <p>Here the <tt>super</tt> keyword is
1260 used in the constructor to initialize the base class. The user is required to
1261 call <tt>super</tt> first in the constructor.</p>
1263 <p>As you can see in this example, you can call the
1264 base class' member functions. You can find all member functions in the base class,
1265 but you will have to give the this-pointer (<tt>self</tt>) as first argument.</p>
1267 <h2><a name="class_lua_derive"></a>deriving in lua</h2>
1269 <p>It is also possible to derive lua classes from C++
1270 classes, and override virtual functions with lua functions. To do this we have
1271 to create a wrapper class for our C++ base class. This is the class that will
1272 hold the lua object when we instantiate a lua class.</p>
1274 <p>The wrapper class has to provide the same constructors
1275 as the base class, with the addition of one extra parameter: <tt>luabind::object</tt>.
1276 This is the reference to the lua object that should be held by the wrapper, and should
1277 be stored in a member variable as done in the sample below.</p>
1279 <pre>
1280 class base class
1282 public:
1283 baseclass(const char* s) { std::cout &lt;&lt; s &lt;&lt; "\n"; }
1284 virtual void f(int a) { std::cout &lt;&lt; "f(" &lt;&lt; a &lt;&lt; ")\n"; }
1287 struct baseclass_wrapper: baseclass
1289 luabind::object m_l;
1290 baseclass_wrapper(luabind::object l, const char* s): baseclass(s), m_l(l) {}
1292 virtual void f(int a) { call_member&lt;void&gt;(m_l, "f", a); }
1293 static void f_static(baseclass* ptr, int a)
1295 return ptr-&gt;baseclass::f(a);
1298 </pre>
1299 <pre>
1300 module(L)
1302 class_&lt;baseclass, baseclass_wrapper&gt;("baseclass")
1303 .def(constructor&lt;const char*&gt;())
1304 .def("f", &amp;baseclass_wrapper::f_static)
1306 </pre>
1308 <p>Note that if you have both base classes and a base class
1309 wrapper, you must give both <tt>bases</tt> and the
1310 base class wrapper type as template parameter to <tt>class_</tt>. The order
1311 in which you specify them is not important.</p>
1313 <p>If we didn't have a class wrapper, it would not be possible to pass a lua class
1314 back to C++. Since the entry points of the virtual functions would still point to
1315 the C++ base class, and not to the functions defined in lua. That's why we need
1316 one function that calls the base class' real function (used if the lua class
1317 doesn't redefine it) and one virtual function that dispatches the call into luabind,
1318 to allow it to select if a lua function should be called, or if the original
1319 function should be called. If you don't intend to derive from a C++ class, or if
1320 it doesn't have any virtual member functions, you can register it without a
1321 class wrapper.</p>
1323 <p>You don't need to have a class wrapper in order to derive from a class,
1324 but if it has virtual functions you may have silent errors. The rule of thumb is:
1325 If your class has virtual functions, create a wrapper type, if it doesn't don't create
1326 a wrapper type.</p>
1328 <h2><a name="class_lua_operators"></a>overloading operators</h2>
1330 <p>You can overload most operators in lua for your classes. You do this by simply declaring
1331 a member function with the same name as an operator (the name of the metamethods in lua). The operators
1332 you can overload are:</p>
1334 <ul>
1335 <li><tt>__add</tt>
1336 <li><tt>__sub</tt>
1337 <li><tt>__mul</tt>
1338 <li><tt>__div</tt>
1339 <li><tt>__pow</tt>
1340 <li><tt>__lt</tt>
1341 <li><tt>__le</tt>
1342 <li><tt>__eq</tt>
1343 <li><tt>__call</tt>
1344 <li><tt>__unm</tt>
1345 <li><tt>__tostring</tt>
1346 </ul>
1348 <p><tt>__tostring</tt> isn't really an operator, but it's the metamethod that is called by the standard
1349 library's <tt>tostring()</tt> function. There's one strange behavior regarding binary operators. You are not
1350 guaranteed that the self pointer you get actually refers to an instance of your class. This is because
1351 lua doesn't distinguish the two cases where you get the other operand as left hand value or right hand value.
1352 Consider the following examples:</p>
1354 <pre>
1355 class 'my_class'
1357 function my_class:__init(v)
1358 self.val = v
1361 function my_class:__sub(v)
1362 return my_class(self.val - v.val)
1365 function my_class:__tostring()
1366 return self.val
1368 </pre>
1370 <p>This will work well as long as you only subtracts instances of <tt>my_class</tt> with each other. But
1371 If you want to be able to subtract ordinary numbers from your class too, you have to manually check the type
1372 of <b>both</b> operands, including the self object.</p>
1374 <pre>
1375 function my_class:__sub(v)
1376 if (type(self) == 'number') then
1377 return my_class(self - v.val)
1379 elseif (type(v) == 'number') then
1380 return my_class(self.val - v)
1382 else
1383 -- assume both operands are instances of my_class
1384 return my_class(self.val - v.val)
1388 </pre>
1390 <p>The reason why <tt>__sub</tt> is used as an example is because subtraction is not commutative (the
1391 order of the operands matter). That's why luabind cannot change order of the operands to make the
1392 self reference always refer to the actual class instance.</p>
1394 <p>If you have two different lua classes with an overloaded operator, the operator of the right hand
1395 side type will be called. If the other operand is a C++ class with the same operator overloaded, it
1396 will be prioritized over the lua class' operator. If none of the C++ overloads matches, the lua
1397 class' operator will be called.</p>
1399 <h2><a name="class_lua_finalizers"></a>finalizers</h2>
1401 <p>If an object needs to perform actions when it's collected we provide
1402 a <tt>__finalize</tt> function that can be overridden in lua-classes.
1403 The __finalize functions will be called on all classes in the inheritance
1404 chain, starting with the most derived type.</p>
1406 <pre>
1409 function lua_testclass:__finalize()
1410 -- called when the an object is collected
1412 </pre>
1414 <h1><a name="exceptions"></a>Exceptions</h1>
1415 <p>If any of the functions you register throws an exception when called, that exception will be caught
1416 by luabind and converted to an error string and <tt>lua_error</tt> will be invoked. If the exception
1417 is a <tt>std::exception</tt> or a <tt>const&nbsp;char*</tt> the string that is pushed on the lua stack,
1418 as error message, will be the <tt>what()</tt> or the string itself respectively. If the exception
1419 is unknown, a generic string saying that the function threw an exception will be pushed.</p>
1421 <p>Exceptions thrown from user defined functions have to be caught by luabind. If they weren't they
1422 would be thrown through lua itself, which is usually compiled as C code and doesn't support the
1423 stack-unwinding that exceptions imply.</p>
1425 <p>Any function that invokes lua code may throw <tt>luabind::error</tt>. This exception means that a lua
1426 run-time error occurred. The error message is found on top of the lua stack. The reason why the
1427 exception doesn't contain the error string itself is because it would then require heap allocation
1428 which may fail. If an exception class throws an exception while it is being thrown itself, the
1429 application will be terminated.</p>
1431 <p>Error's synopsis is:</p>
1433 <pre>
1434 class error: std::exception
1436 public:
1437 error(lua_State*);
1438 lua_State* state() const throw();
1439 virtual const char* what() const throw();
1441 </pre>
1443 <p>The state function returns a pointer to the lua state in which the error was thrown. This pointer
1444 may be invalid if you catch this exception after the lua state is destructed. If the lua state is
1445 valid you can use it to retrieve the error message from the top of the lua stack.</p>
1447 <p>An example of where the lua state pointer may point to an invalid state follows:</p>
1449 <pre>
1450 struct lua_state
1452 lua_state(lua_State* L): m_L(L) {}
1453 ~lua_state() { lua_close(m_L); }
1454 operator lua_State*() { return m_L; }
1455 lua_State* m_L;
1458 int main()
1462 lua_state L = lua_open();
1463 /* ... */
1465 catch(luabind::error&amp; e)
1467 lua_State* L = e.state();
1468 // L will now point to the destructed
1469 // lua state and be invalid
1470 /* ... */
1473 </pre>
1475 <p>There's another exception that luabind may throw. <tt>luabind::cast_failed</tt>, this exception
1476 is thrown from <a href="#lua_fun"><tt>call_function</tt></a>, <a href="#lua_fun"><tt>call_member</tt></a> or when <a href="#functor"><tt>functor</tt></a> is invoked.
1477 It means that the return value from the lua function couldn't be converted to a C++ value. It is
1478 also thrown from <a href="#object_functions"><tt>object_cast</tt></a> if the cast cannot be made.</p>
1480 <p>The synopsis for <tt>luabind::cast_failed</tt> is:</p>
1482 <pre>
1483 class cast_failed: std::exception
1485 public:
1486 cast_failed(lua_State*);
1487 lua_State* state() const throw();
1488 LUABIND_TYPE_INFO info() const throw();
1489 virtual const char* what() const throw();
1491 </pre>
1493 <p>Again, the <tt>state</tt> member function returns a pointer to the lua state where the error occurred.
1494 See the example above to see where this pointer may be invalid.</p>
1496 <p>The <tt>info</tt> member function returns the user defined <a href="#luabind_type_info"><tt>LUABIND_TYPE_INFO</tt></a>, which
1497 defaults to a <tt>const&nbsp;std::type_info*</tt>. This type info describes the type that we tried
1498 to cast a lua value to.</p>
1500 <p>If you have defined <a href="#luabind_no_exceptions"><tt>LUABIND_NO_EXCEPTIONS</tt></a> none of these exceptions will be thrown,
1501 instead you can set two callback functions that are called instead. These two functions are only defined if <a href="#luabind_no_exceptions"><tt>LUABIND_NO_EXCEPTIONS</tt></a> are defined.</p>
1503 <h3><a name="set_error_callback"></a><tt>luabind::set_error_callback(void(*)(lua_State*))</tt></h3>
1504 <p>The function you set will be called when a runtime-error occur in lua code. You can find an
1505 error message on top of the lua stack. This function is not expected to return, if it does
1506 luabind will call <tt>std::terminate()</tt>.</p>
1508 <h3><a name="set_cast_failed_callback"></a><tt>luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))</tt></h3>
1510 <p>The function you set is called instead of throwing <tt>cast_failed</tt>. This function is not expected to return, if it does luabind will call <tt>std::terminate()</tt>.</p>
1513 <h1><a name="policies"></a>Parameter policies</h1>
1515 <p>Sometimes it is necessary to control how luabind passes
1516 arguments and return value, to do this we have policies. These are the
1517 policies that can be used:</p>
1519 <h2><a name="policies_copy"></a>copy</h2>
1521 <p>This will make a copy of the parameter. This is the
1522 default behavior when passing parameters by-value. Note that this can only be
1523 used when passing from C++ to lua. This policy requires that the parameter
1524 type has a copy constructor.</p>
1526 <p>To use this policy you need to include <tt>&lt;luabind/copy_policy.hpp&gt;</tt>.</p>
1528 <h2><a name="policies_adopt"></a>adopt</h2>
1530 <p>This will transfer ownership of the parameter.</p>
1531 <p>Consider making a factory function in C++ and exposing
1532 it to lua:</p><pre>base* create_base()
1534 return new base();
1536 </pre>
1538 <pre>
1539 module(L)
1541 def("create_base", create_base)
1543 </pre>
1545 <p>Here we need to make sure lua understands that it should
1546 adopt the pointer returned by the factory-function. This can be done using the
1547 adopt-policy.</p>
1549 <pre>
1550 module(L)
1552 def(L, "create_base", adopt(return_value))
1554 </pre>
1556 <p>To specify multiple policies we just separate them with '+'.</p>
1558 <pre>
1559 base* set_and_get_new(base* ptr)
1561 base_ptrs.push_back(ptr);
1562 return new base();
1564 </pre>
1566 <pre>
1567 module(L)
1569 def(L, "set_and_get_new", &amp;set_and_get_new, adopt(return_value) + adopt(_1))
1571 </pre>
1573 <p>When lua adopts a pointer, it will call <tt>delete</tt> on it. This means that it cannot adopt pointers allocated with
1574 another allocator than <tt>new</tt> (no <tt>malloc</tt> for example).</p>
1576 <p>To use this policy you need to include <tt>&lt;luabind/adopt_policy.hpp&gt;</tt>.</p>
1578 <h2><a name="policies_dependency"></a>dependency</h2>
1580 <p>The dependency policy is used to create life-time dependencies between values. Consider the following example:</p>
1582 <pre>
1583 struct A
1585 B m_member;
1587 const B&amp; get_member()
1589 return m_member;
1592 </pre>
1594 <p>When wrapping this class, we would do something like:</p>
1596 <pre>
1597 module(L)
1599 class_&lt;A&gt;("A")
1600 .def(constructor&lt;&gt;())
1601 .def("get_member", &amp;A::get_member)
1603 </pre>
1605 <p>However, since the return value of get_member is a reference to a member of A, this will create
1606 some life-time issues. For example:</p>
1608 <pre>
1609 a = A()
1610 b = a:get_member() -- b points to a member of a
1611 a = nil
1612 collectgarbage(0) -- since there are no references left to a, it is removed
1613 -- at this point, b is pointing into a removed object
1614 </pre>
1616 <p>When using the dependency-policy, it is possible to tell luabind to tie the lifetime of one
1617 object to another, like this:</p>
1619 <pre>
1620 module(L)
1622 class_&lt;A&gt;("A")
1623 .def(constructor&lt;&gt;())
1624 .def("get_member", &amp;A::get_member, dependency(result, self))
1626 </pre>
1628 <p>This will create a dependency between the return-value of the function, and the self-object. This means
1629 that the self-object will be kept alive as long as the result is still alive.</p>
1631 <pre>
1632 a = A()
1633 b = a:get_member() -- b points to a member of a
1634 a = nil
1635 collectgarbage(0) -- a is dependent on b, so it isn't removed
1636 b = nil
1637 collectgarbage(0) -- all dependencies to a gone, a is removed
1638 </pre>
1640 <p>To use this policy you need to include <tt>&lt;luabind/dependency_policy.hpp&gt;</tt>.</p>
1642 <h2><a name="policies_return_ref"></a>return_reference_to</h2>
1644 <p>It is very common to return references to arguments or the this-pointer to allow for chaining in C++.</p>
1645 <pre>
1646 struct A
1648 float m_val;
1650 A&amp; set(float v)
1652 m_val = v;
1653 return *this;
1656 </pre>
1658 <p>When luabind generates code for this, it will create a new object for the return-value, pointing to the self-object. This
1659 isn't a problem, but could be a bit inefficient. When using the return_reference_to-policy we have the ability to tell
1660 luabind that the return-value is already on the lua stack.</p>
1662 <pre>
1663 module(L)
1665 class_&lt;A&gt;("A")
1666 .def(constructor&lt;&gt;())
1667 .def("set", &amp;A::set, return_reference_to(self))
1669 </pre>
1671 <p>Instead of creating a new object, luabind will just copy the object that is already on the stack.</p>
1672 <p>NOTE! This policy ignores all type information and should be used only it situations where the parameter type
1673 is a perfect match to the return-type (such as in the example).</p>
1675 <p>To use this policy you need to include <tt>&lt;luabind/return_reference_to_policy.hpp&gt;</tt>.</p>
1677 <h2><a name="policies_out"></a>out_value</h2>
1679 <p>This policy makes it possible to wrap functions that take non const references as its parameters with the intention to write return values to them.</p>
1681 <pre>
1682 void f(float&amp; val) { val = val + 10.f; }
1683 </pre>
1685 <pre>
1686 void f(float* val) { *val = *val + 10.f; }
1687 </pre>
1689 <p>Can be wrapped by doing:</p>
1691 <pre>
1692 module(L)
1694 def("f", &amp;f, out_value(_1))
1696 </pre>
1698 <p>When invoking this function from lua it will return the value assigned to its parameter.</p>
1700 <pre>
1701 a = f(10) -- a is now 20
1702 </pre>
1704 <p>When this policy is used in conjunction with user define types we often need to do ownership transfers.</p>
1706 <pre>
1707 struct A
1711 void f(A*&amp; obj) { obj = new A(); }
1713 void f(A** obj) { *obj = new A(); }
1714 </pre>
1716 <p>Here we need to make sure luabind takes control over object returned, for this we use the <tt>adopt</tt> policy</p>
1718 <pre>
1719 module(L)
1721 class_&lt;A&gt;("A"),
1723 def("f", &amp;f, out_value(_1, adopt(_2)))
1725 </pre>
1727 <p>Here we are using <tt>adopt</tt> as an internal policy to <tt>out_value</tt>. The index specified, <tt>_2</tt>, means adopt will be used to convert the value back to lua. Using <tt>_1</tt> means the policy will be used when converting from lua to C++.</p>
1729 <p>To use this policy you need to include <tt>&lt;luabind/out_value_policy.hpp&gt;</tt>.</p>
1731 <h2><a name="policies_pure_out"></a>pure_out_value</h2>
1733 <p>This policy works in exactly the same way as <tt>out_value</tt>, except that it replaces the parameters with default-constructed
1734 objects.</p>
1736 <pre>
1737 void get(float&amp; x, float&amp; y)
1739 x = 3.f;
1740 y = 4.f;
1742 </pre>
1743 <pre>
1744 module(L)
1746 def("get", &amp;get, pure_out_value(_1) + pure_out_value(_2))
1748 </pre>
1749 <pre>
1750 x,y = get()
1751 print(x,y) -- prints '3 4'
1752 </pre>
1754 <p>Like out_value, it is possible to specify an internal policy used then converting the values back to lua.</p>
1756 <pre>
1757 void get(test_class*&amp; obj)
1759 obj = new test_class();
1761 </pre>
1762 <pre>
1763 module(L)
1765 def("get", &amp;get, pure_out_value(_1, adopt(_1)))
1767 </pre>
1769 <h2><a name="policies_discard_result"></a>discard_result</h2>
1771 <p>This is a very simple policy which makes it possible to throw away the value returned by a C++ function, instead of converting it to lua. This example makes sure the <tt>this</tt> reference never gets converted to lua</p>
1773 <pre>
1774 struct simple
1776 simple&amp; set_name(const std::string&amp; n)
1778 name = n;
1779 return *this;
1782 std::string name;
1784 </pre>
1785 <pre>
1786 module(L)
1788 class_&lt;simple&gt;("simple")
1789 .def("set_name", &amp;simple::set_name, discard_result)
1791 </pre>
1793 <p>To use this policy you need to include <tt>&lt;luabind/discard_result_policy.hpp&gt;</tt>.</p>
1795 <h2><a name="policies_return_stl_iterator"></a>return_stl_iterator</h2>
1797 <p>This policy converts an STL container to a generator function that can be used in lua to
1798 iterate over the container. It works on any container that defines <tt>begin()</tt> and <tt>end()</tt>
1799 member functions (they have to return iterators). It can be used like this:</p>
1801 <pre>
1802 struct A
1804 std::vector&lt;std::string&gt; names;
1806 </pre>
1807 <pre>
1808 module(L)
1810 class_&lt;A&gt;("A")
1811 .def_readwrite("names", &amp;A::names, return_stl_iterator)
1813 </pre>
1815 <p>The lua code to iterate over the container:</p>
1817 <pre>
1818 a = A()
1820 for name in a.names do
1821 print(name)
1823 </pre>
1825 <p>To use this policy you need to include <tt>&lt;luabind/iterator_policy.hpp&gt;</tt></p>
1827 <h2><a name="policies_yield"></a>yield</h2>
1829 <p>This policy will cause the function to always yield the current
1830 thread when returning. See the lua manual for restrictions on yield.</p>
1832 <pre>
1833 module(L)
1835 def("f", &amp;f, yield)
1837 </pre>
1839 <h2><a name="policies_custom"></a>custom</h2>
1841 <p>The policies don't have a stable API yet. See the examples directory.</p>
1843 <h2><a name="policies_user_converter"></a>user defined converter</h2>
1845 <p>The policies don't have a stable API yet. See the examples directory.</p>
1847 <h1><a name="examples"></a>Examples</h1>
1849 <p>This section contains examples of how a class and function bind could look
1850 like in C++ and how they can be used from lua. Most of these examples requires
1851 some external libraries that they bind to lua.</p>
1853 <p>These examples will also be found in the distribution along with makefiles.</p>
1855 <h2><a name="examples_cln"></a>Class Library for Numbers</h2>
1857 <p>Class Library for Numbers (CLN) is a library that implements large values and arithmetic operations
1858 on them, see its <a href="http://www.ginac.de/CLN/">homepage</a> for more details.</p>
1860 <p>This example bind a very small part of the library.</p>
1862 <pre>
1863 #include &lt;cln/cln.h&gt;
1865 extern "C"
1867 #include "lua.h"
1868 #include "lualib.h"
1869 #include "lauxlib.h"
1872 #include &lt;luabind/luabind.hpp&gt;
1874 void bind_cln(lua_State* L)
1876 using namespace luabind;
1877 using namespace cln;
1879 module(L)
1881 // real numbers
1882 class_&lt;cl_R&gt;("cl_R")
1883 .def(constructor&lt;&gt;())
1884 .def(constructor&lt;const cl_I&amp;&gt;())
1885 .def(constructor&lt;float&gt;())
1886 .def(constructor&lt;const char*&gt;())
1887 .def(tostring(const_self))
1888 .def(-self)
1889 .def(const_self + const_self)
1890 .def(const_self - const_self)
1891 .def(const_self * const_self)
1892 .def(const_self / const_self)
1893 .def(const_self &lt;= const_self)
1894 .def(const_self &lt; const_self)
1895 .def(const_self == const_self)
1896 .def(other&lt;int&gt;() + const_self)
1897 .def(other&lt;int&gt;() - const_self)
1898 .def(other&lt;int&gt;() * const_self)
1899 .def(other&lt;int&gt;() / const_self)
1900 .def(other&lt;int&gt;() &lt;= const_self)
1901 .def(other&lt;int&gt;() &lt; const_self)
1902 .def(const_self + other&lt;int&gt;())
1903 .def(const_self - other&lt;int&gt;())
1904 .def(const_self * other&lt;int&gt;())
1905 .def(const_self / other&lt;int&gt;())
1906 .def(const_self &lt;= other&lt;int&gt;())
1907 .def(const_self &lt; other&lt;int&gt;())
1910 // rational numbers
1911 class_&lt;cl_RA, cl_R&gt;("cl_RA")
1912 .def(constructor&lt;&gt;())
1913 .def(constructor&lt;const cl_I&amp;&gt;())
1914 .def(constructor&lt;int&gt;())
1915 .def(constructor&lt;const char*&gt;())
1916 .def(tostring(const_self))
1917 .def(-self)
1918 .def(const_self + const_self)
1919 .def(const_self - const_self)
1920 .def(const_self * const_self)
1921 .def(const_self / const_self)
1922 .def(const_self &lt;= const_self)
1923 .def(const_self &lt; const_self)
1924 .def(const_self == const_self)
1925 .def(other&lt;int&gt;() + const_self)
1926 .def(other&lt;int&gt;() - const_self)
1927 .def(other&lt;int&gt;() * const_self)
1928 .def(other&lt;int&gt;() / const_self)
1929 .def(other&lt;int&gt;() &lt;= const_self)
1930 .def(other&lt;int&gt;() &lt; const_self)
1931 .def(const_self + other&lt;int&gt;())
1932 .def(const_self - other&lt;int&gt;())
1933 .def(const_self * other&lt;int&gt;())
1934 .def(const_self / other&lt;int&gt;())
1935 .def(const_self &lt;= other&lt;int&gt;())
1936 .def(const_self &lt; other&lt;int&gt;())
1939 // integers
1940 class_&lt;cl_I, cl_RA&gt;("cl_I")
1941 .def(constructor&lt;&gt;())
1942 .def(constructor&lt;const cl_I&amp;&gt;())
1943 .def(constructor&lt;int&gt;())
1944 .def(constructor&lt;const char*&gt;())
1945 .def(tostring(const_self))
1946 .def(-self)
1947 .def(const_self + const_self)
1948 .def(const_self - const_self)
1949 .def(const_self * const_self)
1950 .def(const_self &lt;= const_self)
1951 .def(const_self &lt; const_self)
1952 .def(const_self == const_self)
1953 .def(other&lt;int&gt;() + const_self)
1954 .def(other&lt;int&gt;() - const_self)
1955 .def(other&lt;int&gt;() * const_self)
1956 .def(other&lt;int&gt;() &lt;= const_self)
1957 .def(other&lt;int&gt;() &lt; const_self)
1958 .def(const_self + other&lt;int&gt;())
1959 .def(const_self - other&lt;int&gt;())
1960 .def(const_self * other&lt;int&gt;())
1961 .def(const_self &lt;= other&lt;int&gt;())
1962 .def(const_self &lt; other&lt;int&gt;())
1965 def("factorial", &amp;cln::factorial),
1966 def("sqrt", (const cl_R(*)(const cl_R&amp;))&amp;cln::sqrt)
1970 int main()
1972 lua_State* L = lua_open();
1973 lua_baselibopen(L);
1974 lua_mathlibopen(L);
1975 luabind::open(L);
1977 bind_cln(L);
1979 lua_dofile(L, "cln_test.lua");
1981 lua_close(L);
1982 return 0;
1984 </pre>
1986 cln_test.lua may look like this:
1988 <pre>
1989 a = factorial(41)
1990 b = factorial(42)
1992 print('a = fac(41) = ' .. tostring(a))
1993 print('b = fac(42) = ' .. tostring(b))
1994 print('b / a = ' .. tostring(b / a))
1996 c = a * 42
1998 d = sqrt(cl_R(10))
2000 print('d = sqrt(10) = ' .. tostring(d))
2001 </pre>
2003 As you might have figured out, the factorial of 41 will be a really large number. The output from this script will be:
2005 <pre>
2006 a = fac(41) = 33452526613163807108170062053440751665152000000000
2007 b = fac(42) = 1405006117752879898543142606244511569936384000000000
2008 b / a = 42
2009 d = sqrt(10) = 3.1622777
2010 </pre>
2011 <h1><a name="config"></a>Configuration</h1>
2013 <p>There are a number of configuration options available when building luabind. It is very important
2014 that your project has the exact same conmfiguration options as the ones given when the library was build!
2015 The exceptions are the <tt>LUABIND_MAX_ARITY</tt> and <tt>LUABIND_MAX_BASES</tt> which are template-based
2016 options and only matters when you use the library (which means they can differ from the settings of the
2017 library).</p>
2019 <p>The default settings can be found in <tt>luabind/config.hpp</tt> they will be used if no other settings
2020 are given.</p>
2022 <p>If you want to change the settings of the library, you can modify the config-file. It is included and used
2023 by all make-files. You can change paths to lua and boost in there as well.</p>
2025 <h3><tt>LUABIND_MAX_ARITY</tt></h3>
2026 <p>Controls the maximum arity of functions that are registered
2027 with luabind. You can't register functions that takes more
2028 parameters than the number this macro is set to. It defaults
2029 to 5, so, if your functions have greater arity you have to
2030 redefine it. A high limit will increase compilation time.</p>
2031 <h3><tt>LUABIND_MAX_BASES</tt></h3>
2032 <p>Controls the maximum number of classes one class can derive from
2033 in luabind (the number of classes specified within
2034 <tt>bases&lt;&gt;</tt>). <tt>LUABIND_MAX_BASES</tt> defaults to 4.
2035 A high limit will increase compilation time.</p>
2036 <h3><tt>LUABIND_NO_ERROR_CHECKING</tt></h3>
2037 <p>If this macro is defined, all the lua code is expected only to make
2038 legal calls. If illegal function calls are made (e.g. giving parameters
2039 that doesn't match the function signature) they will not be detected
2040 by luabind and the application will probably crash. Error checking
2041 could be disabled when shipping a release build (given that no end-user
2042 has access to write custom lua code). Note that function parameter
2043 matching will be done if a function is overloaded, since otherwise it's
2044 impossible to know which one was called. Functions will still be able
2045 to throw exceptions when error checking is disabled.</p>
2047 <p>If a functions throws an exception it will be
2048 caught by luabind and propagated with <tt>lua_error()</tt>.</p>
2051 <h3><tt>LUABIND_DONT_COPY_STRINGS</tt></h3>
2052 <p>If this macro is defined, luabind will expect that all strings given
2053 to the def() methods are static constant strings (given as string
2054 constants for example). luabind will not copy the strings if you
2055 enable this setting, but just keep the char pointers. This may be
2056 especially useful for embedded systems or consoles where heap
2057 allocations should be minimized.</p>
2060 <a name="luabind_no_exceptions"></a><h3><tt>LUABIND_NO_EXCEPTIONS</tt></h3>
2061 <p>This define will disable all usage of try, catch and throw in
2062 luabind. This will in many cases disable run-time errors, when
2063 performing invalid casts or calling lua-functions that fails or
2064 returns values that cannot be converted by the given policy.
2065 luabind requires that no function called directly or indirectly
2066 by luabind throws an exception (throwing exceptions through
2067 lua has undefined behavior).</p>
2069 <p>Where exceptions are the only way to get an error report from
2070 luabind, they will be replaced with calls to the callback
2071 functions set byt <a href="#set_error_callback"><tt>set_error_callback()</tt></a>
2072 and <a href="#set_cast_failed_callback"><tt>set_cast_failed_callback()</tt></a>.</p>
2075 <a name="lua_api"></a><h3><tt>LUA_API</tt></h3>
2076 <p>If you want to link dynamically against lua, you can set this define
2077 to the import-keyword on your compiler and platform. On windows in devstudio
2078 this should be <tt>__declspec(dllimport)</tt> if you want to link against lua as a dll.
2080 <a name="luabind_dll"></a><h3><tt>LUABIND_EXPORT</tt><br>
2081 <tt>LUABIND_IMPORT</tt></h3>
2082 <p>If you want to link against luabind as a dll (in devstudio), you can define
2083 <tt>LUABIND_EXPORT</tt> to <tt>__declspec(dllexport)</tt> and <tt>LUABIND_IMPORT</tt>
2084 to <tt>__declspec(dllimport)</tt>. Note that you have o link against lua as a dll
2085 aswell, to make it work.</p>
2088 <a name="luabind_type_info"></a><h3><tt>LUABIND_TYPE_INFO</tt><br>
2089 <tt>LUABIND_TYPE_INFO_EQUAL(i1,i2)</tt><br>
2090 <tt>LUABIND_TYPEID(t)</tt><br>
2091 <tt>LUABIND_INVALID_TYPE_INFO</tt></h3>
2092 <p>If you don't want to use the RTTI supplied by C++
2093 you can supply your own type-info structure with the
2094 LUABIND_TYPE_INFO define. Your type-info structure must
2095 be copyable and must be able to compare itself against
2096 other type-info structures. You supply the compare
2097 function through the LUABIND_TYPE_INFO_EQUAL()
2098 define. It should compare the two type-info structures
2099 it is given and return true if they represent the same type
2100 and false otherwise. You also have to supply a function
2101 to generate your type-info structure. You do this through
2102 the LUABIND_TYPEID() define. It should return your type-info
2103 structure and it takes a type as its parameter. That is,
2104 a compile time parameter. LUABIND_INVALID_TYPE_INFO macro
2105 should be defined to an invalid type. No other type should
2106 be able to produce this type info. To use it you probably
2107 have to make a traits class with specializations for all
2108 classes that you have type-info for. Like this:</p>
2110 <pre>
2111 class A;
2112 class B;
2113 class C;
2115 template&lt;class T&gt; struct typeinfo_trait;
2117 template&lt;&gt; struct typeinfo_trait&lt;A&gt; { enum { type_id = 0 }; };
2118 template&lt;&gt; struct typeinfo_trait&lt;B&gt; { enum { type_id = 1 }; };
2119 template&lt;&gt; struct typeinfo_trait&lt;C&gt; { enum { type_id = 2 }; };
2120 </pre>
2122 <p>If you have set up your own RTTI system like this (by using integers to identify types)
2123 you can have luabind use it with the following defines</p>
2125 <pre>
2126 #define LUABIND_TYPE_INFO int
2127 #define LUABIND_TYPE_INFO_EQUAL(i1, i2) i1 == i2
2128 #define LUABIND_TYPEID(t) typeinfo_trait&lt;t&gt;::type_id
2129 #define LUABIND_INVALID_TYPE_INFO -1
2130 </pre>
2132 <p>The default behavior, if you don't define any of these three, is to use the built-in
2133 RTTI support in C++.</p>
2135 <pre>
2136 #define LUABIND_TYPE_INFO const std::type_info*
2137 #define LUABIND_TYPEID(t) &amp;typeid(t)
2138 #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
2139 #define LUABIND_INVALID_TYPE_INFO &amp;typeid(detail::null_type)
2140 </pre>
2142 <p>currently the type given through LUABIND_TYPE_INFO must be less-than comparable!</p>
2143 <h3><tt>NDEBUG</tt></h3>
2144 <p>This define will disable all asserts and should be defined in a release build.</p>
2147 <h1><a name="implementation_notes"></a>Implementation notes</h1>
2149 <p>The classes and objects are implemented as user data in lua. To make sure that
2150 the user data really is the internal structure it is supposed to be, we tag their
2151 metatables. A user data who's metatable contains a boolean member named
2152 <tt>"__luabind_classrep"</tt> is expected to be a class exported by luabind.
2153 A user data who's metatable contains a boolean member named <tt>"__luabind_class"</tt>
2154 is expected to be an instantiation of a luabind class.</p>
2156 <p>This means that if you make your own user data and tags its metatable with the
2157 exact same names, you can very easily fool luabind and crash the application.</p>
2159 <p>In the lua registry, luabind keeps an entry called "<tt>__luabind_classes</tt>".
2160 It should not be removed or overwritten.</p>
2162 <p>In the global table, a variable called <tt>super</tt> is used every time a constructor
2163 in a lua-class is called. This is to make it easy for that constructor to call its base
2164 class' constructor. So, if you have a global variable named <tt>super</tt> it may very
2165 well be overwritten. This is probably not the best solution, and this restriction may very
2166 well be removed in the future.</p>
2168 <p>Luabind uses two upvalues for functions that it registers. The first is a userdata containing
2169 a list of overloads for the function, the other is a light userdata with the value <tt>0x1337</tt>,
2170 this last value is used to identify functions registered by luabind. It should be virtually impossible
2171 to have such a pointer as secondary upvalue by pure chance. This means, if you are trying to replace
2172 an existing function with a luabind function, luabind will see that the secondary upvalue isn't
2173 the magical id number and replaces it.</p>
2175 <p>Inside the <tt>luabind</tt> namespace, there's another namespace called <tt>detail</tt>.
2176 This namespace contains non-public classes and are not supposed to be used directly.</p>
2178 <h1><a name="error_messages"></a>Error messages</h1>
2180 <ul>
2181 <li>cannot set attribute '<i>&lt;class-name&gt;</i>.<i>&lt;attribute-name&gt;</i>'
2182 <p>There is no data member named <i>&lt;attribute-name&gt;</i> in the class <i>&lt;class-name&gt;</i>, or
2183 there's no setter-method registered on that property name. See the <a href="#class_property">properties</a> section.</p>
2185 <li><i>&lt;class-name&gt;</i>() threw an exception
2186 <li><i>&lt;class-name&gt;</i>:<i>&lt;function-name&gt;</i>() threw an exception
2187 <p>The class' constructor or member function threw an unknown exception. Known exceptions are <tt>const&nbsp;char*</tt>,
2188 <tt>std::exception</tt>. See the <a href="#exceptions">exceptions</a> section.</p>
2190 <li>no overload of '<i>&lt;class-name&gt;</I>:<i>&lt;function-name&gt;</i>' matched the arguments (&lt;<i>parameter-types&gt;)</i>
2191 <li>no match for function call '<i>&lt;function-name&gt;</i>' with the parameters (<i>&lt;parameter-types&gt;</i>)
2192 <li>no constructor of <i>&lt;class-name&gt;</i> matched the arguments (<i>&lt;parameter-types&gt;</i>)
2193 <li>no operator <i>&lt;operator-name&gt;</i> matched the arguments (<i>&lt;parameter-types&gt;</i>)
2194 <p>No function/operator with the given name takes the parameters you gave it. You have either misspelled the function name,
2195 or given it incorrect parameters. This error is followed by a list of possible candidate functions to help you figure out what
2196 parameter has the wrong type. If the candidate list is empty there's no function at all with that name. See the
2197 <a href="#fun_sigmatch">signature matching</a> section.</p>
2199 <li>call of overloaded '<i>&lt;class-name&gt;</i>:<i>&lt;function-name&gt;</i>(&lt;<i>parameter-types&gt;</i>)' is ambiguous
2200 <li>ambiguous match for function call '<i>&lt;function-name&gt;</i>' with the parameters (<i>&lt;parameter-types&gt;</i>)
2201 <li>call of overloaded constructor '<i>&lt;class-name&gt;</i>(<i>&lt;parameter-types&gt;</i>)' is ambiguous
2202 <li>call of overloaded operator <i>&lt;operator-name&gt;</i> (<i>&lt;parameter-types&gt;</i>) is ambiguous
2203 <p>This means that the function/operator you are trying to call has at least one other overload that matches the arguments
2204 just as good as the first overload.</p>
2206 <li>cannot derive from C++ class '<i>&lt;class-name&gt;</i>'. It does not have a wrapped type.
2207 <p>You are trying to derive a lua class from a C++ class that doesn't have a wrapped type. You have to give
2208 your C++ class a wrapped type when you register it with lua. See the <a href="#class_lua_derive">deriving in lua</a> section.</p>
2210 <li>derived class must call super on base
2211 <li>cannot set property '<i>&lt;class-name&gt;</i>.<i>&lt;attribute_name&gt;</i>' because it's read only
2212 <p>The attribute you are trying to set is registered as read only. If you want it to be writeable you have to change your
2213 class registration and use <tt>def_readwrite()</tt> instead of <tt>def_readonly()</tt>. Alternatively (if your attribute
2214 is a property with getter and setter functions), you have to give a setter function when declaring your attribute. See
2215 the <a href="#class_property">properties</a> section.</p>
2217 <li>no static '<i>&lt;enum-name&gt;</i>' in class '<i>&lt;class-name&gt;</i>'
2218 <p>You will get this error message if you are trying to access an enum that doesn't exist. Read about how to
2219 <a href="#class_enum">declare enums</a>.</p>
2221 <li>expected base class
2222 <p>You have written a malformed <a href="#class_lua">class definition in lua</a>. The format is:
2223 <tt>class&nbsp;'<i>&lt;class-name&gt;</i>'&nbsp;[<i>&lt;base-class&gt;</i>]</tt>. If you don't want to derive from
2224 a base class, you have to break the line directly after the class declaration.</p>
2226 <li>invalid construct, expected class name
2227 <p>You have written a malformed <a href="#class_lua">class definition in lua</a>. The <tt>class</tt> function expects
2228 a string as argument. That string is the name of the lua class to define.</p>
2229 </ul>
2231 <h1><a name="faq"></a>FAQ</h1>
2232 <ul>
2233 <li><h3>What's up with __cdecl and __stdcall?</h3>
2235 <p>If you're having problem with functions that cannot be converted from
2236 <tt>'void&nbsp;(__stdcall&nbsp;*)(int,int)'</tt> to <tt>'void&nbsp;(__cdecl&nbsp;*)(int,int)'</tt>.
2237 You can change the project settings to make the compiler generate functions with
2238 <tt>__cdecl</tt> calling conventions. This is a problem in developer studio.</p>
2240 <li><h3>What's wrong with functions taking variable number of arguments?</h3>
2241 <p>You cannot register a function with ellipses in its signature. Since ellipses don't preserve
2242 type safety, those should be avoided anyway.</p>
2244 <li><h3>Internal structure overflow in VC</h3>
2245 <p>If you, in visual studio, get <tt>fatal error C1204: compiler limit : internal
2246 structure overflow</tt>. You should try to split that compilation unit up
2247 in smaller ones.</p>
2249 <li><h3>What's wrong with precompiled headers in VC?</h3>
2250 <p>Visual Studio doesn't like anonymous namespaces in its precompiled headers. If you encounter this
2251 problem you can disable precompiled headers for the compilation unit (cpp-file) that uses luabind.</p>
2253 <li><h3>error C1076: compiler limit - internal heap limit reached in VC</h3>
2254 <p>In visual studio you will probably hit this error. To fix it you have to increase the internal heap
2255 with a command-line option. We managed to compile the test suit with /Zm300, but you may need a larger
2256 heap then that.</p>
2258 <li><h3>error C1055: compiler limit : out of keys in VC</h3>
2259 <p>It seems that this error occurs when too many <tt>assert()</tt> are used in a program, or more
2260 specifically, the <tt>__LINE__</tt> macro. It seems to be fixed by changing /ZI (Program database
2261 for edit and continue) to /Zi (Program database).</p>
2263 <li><h3>How come my executable is huge?</h3>
2264 <p>If you're compiling in debug mode, you will probably have a lot of debug-info and symbols (luabind
2265 consists of a lot of functions). Also, if built in debug mode, no optimizations were applied, luabind
2266 relies on that the compiler is able to inline functions. If you built in release mode, try running
2267 <tt>strip</tt> on your executable to remove export-symbols, this will trim down the size.</p>
2268 <p>Our tests suggests that cygwin's gcc produces much bigger executables compared to gcc on other
2269 platforms and other compilers.</p>
2270 // check the magic number that identifies luabind's functions
2272 <li><h3>Can I register template classes with luabind?</h3>
2273 <p>Yes you can, but you can only register explicit instantiations of the class. Because there's no
2274 lua counterpart to C++ templates. For example, you can register an explicit instantiation of
2275 <tt>std::vector</tt> like this:</p>
2276 <pre>
2277 module(L)
2279 class_&lt;std::vector&lt;int&gt;&nbsp;&gt;("vector")
2280 .def(constructor&lt;int&gt;)
2281 .def("push_back", &amp;std::vector&lt;int&gt;::push_back)
2283 </pre>
2284 <p>Note that the space between the two &gt; is required by C++.</p>
2286 <li><h3>Do I have to register destructors for my classes?</h3>
2287 <p>No, the destructor of a class is always called by luabind when an object is collected. Note that
2288 lua has to own the object to collect it. If you pass it to C++ and gives up ownership (with
2289 <a href="#policy_adopt">adopt</a> policy) it will no longer be owned by lua, and not collected.</p>
2290 <p>If you have a class hierarchy, you should make the destructor <tt>virtual</tt> if you want to
2291 be sure that the correct destructor is called (this apply to C++ in general).</p>
2293 <li><h3>Fatal Error C1063 compiler limit : compiler stack overflow in VC</h3>
2294 <p>VC6.5 chokes on warnings, if you are getting alot of warnings from your code try suppressing them
2295 with a pragma directive, this should solve the problem.</p>
2297 <li><h3>Crashes when linking against luabind as a dll in windows</h3>
2298 <p>When you build luabind, lua and you project, make sure you link against the runtime dynamically
2299 (as a dll).</p>
2301 <li><h3>I cannot register a function with a non-const parameter</h3>
2302 <p>This is because there is no way to get a reference to a lua value. Have a look at
2303 <a href="#policies_out">out_value</a> and <a href="#policies_pure_out">pure_out_value</a> policies.</p>
2305 </ul>
2307 <h1><a name="future"></a>Future additions</h1>
2308 <ul>
2309 <li>A mechanism for wrapping iterators with generators.
2310 </ul>
2312 <h1><a name="issues"></a>Known issues</h1>
2313 <ul>
2314 <li>There are problems involved in using strings with extra nulls in them as member names.
2315 <li>If one class registers two functions with the same name and the same signature,
2316 there's currently no error. The last registered function will be the one that's used.
2317 <li>In vc7, classes can not be called <tt>test</tt>.
2318 <li>Visual studio have problems selecting the correct overload of <tt>std::swap()</tt> for <tt>luabind::object</tt>.
2319 <li>If you register a function and later renames it, error messages will use the original function name
2320 </ul>
2322 <h1><a name="acknowledgments"></a>Acknowledgments</h1>
2324 <p>This library was written by <a href="mailto:dalwan01@student.umu.se">Daniel Wallin</a>
2325 and <a href="mailto:c99ang@cs.umu.se">Arvid Norberg</a>. &copy; Copyright 2003. All rights reserved.</p>
2327 <p>This library was inspired by Dave Abrahams'
2328 <a href="http://www.boost.org/libs/python/doc/index.html">Boost.Python</a> library which can be found in the
2329 <a href="http://www.boost.org">boost</a> library.</p>
2331 <a href="http://validator.w3.org/check/referer">
2332 <img style="border:0;width:88px;height:31px"
2333 src="http://www.w3.org/Icons/valid-html401"
2334 alt="Valid HTML 4.01!"></a>
2336 <a href="http://jigsaw.w3.org/css-validator/">
2337 <img style="border:0;width:88px;height:31px"
2338 src="http://jigsaw.w3.org/css-validator/images/vcss"
2339 alt="Valid CSS!"></a>
2341 </p>
2343 </body></html>