Hold a weak pointer in instance_holder when ownership is released.
[luabind.git] / doc / docs.rst
blob5e56ae8726e7a83111ee51a399a8df8b45473ebf
1 .. include:: version.rst
3 +++++++++++++++++++
4  luabind |version|
5 +++++++++++++++++++
7 :Author: Daniel Wallin, Arvid Norberg
8 :Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.
9 :License: Permission is hereby granted, free of charge, to any person obtaining a
10           copy of this software and associated documentation files (the "Software"),
11           to deal in the Software without restriction, including without limitation
12           the rights to use, copy, modify, merge, publish, distribute, sublicense,
13           and/or sell copies of the Software, and to permit persons to whom the
14           Software is furnished to do so, subject to the following conditions:
16           The above copyright notice and this permission notice shall be included
17           in all copies or substantial portions of the Software.
19           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20           ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21           TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22           PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23           SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
24           ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25           ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26           OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
27           OR OTHER DEALINGS IN THE SOFTWARE.
30 .. _MIT license: http://www.opensource.org/licenses/mit-license.php
31 .. _Boost: http://www.boost.org
33 Note: This library is currently in public beta phase. This documentation
34 should be considered beta as well. Please report any grammatical 
35 corrections/spelling corrections.
37 .. contents::
38     :depth: 2
39     :backlinks: none
40 .. section-numbering::
42 Introduction
43 ============
45 Luabind is a library that helps you create bindings between C++ and Lua. It has
46 the ability to expose functions and classes, written in C++, to Lua. It will
47 also supply the functionality to define classes in Lua and let them derive from
48 other Lua classes or C++ classes. Lua classes can override virtual functions
49 from their C++ base classes. It is written towards Lua 5.0, and does not work
50 with Lua 4.
52 It is implemented utilizing template meta programming. That means that you
53 don't need an extra preprocess pass to compile your project (it is done by the
54 compiler). It also means you don't (usually) have to know the exact signature 
55 of each function you register, since the library will generate code depending 
56 on the compile-time type of the function (which includes the signature). The 
57 main drawback of this approach is that the compilation time will increase for 
58 the file that does the registration, it is therefore recommended that you 
59 register everything in the same cpp-file.
61 Luabind is released under the terms of the `MIT license`_.
63 We are very interested in hearing about projects that use luabind, please let
64 us know about your project.
66 The main channel for help and feedback is the `luabind mailing list`_.
67 There's also an IRC channel ``#luabind`` on irc.freenode.net.
69 .. _`luabind mailing list`: https://lists.sourceforge.net/lists/listinfo/luabind-user
72 Features
73 ========
75 Luabind supports:
77  - Overloaded free functions 
78  - C++ classes in Lua 
79  - Overloaded member functions 
80  - Operators 
81  - Properties 
82  - Enums 
83  - Lua functions in C++ 
84  - Lua classes in C++ 
85  - Lua classes (single inheritance) 
86  - Derives from Lua or C++ classes 
87  - Override virtual functions from C++ classes 
88  - Implicit casts between registered types 
89  - Best match signature matching 
90  - Return value policies and parameter policies 
93 Portability
94 ===========
96 Luabind has been tested to work on the following compilers:
98  - Visual Studio 7.1 
99  - Visual Studio 7.0 
100  - Visual Studio 6.0 (sp 5) 
101  - Intel C++ 6.0 (Windows) 
102  - GCC 2.95.3 (cygwin) 
103  - GCC 3.0.4 (Debian/Linux) 
104  - GCC 3.1 (SunOS 5.8) 
105  - GCC 3.2 (cygwin) 
106  - GCC 3.3.1 (cygwin)
107  - GCC 3.3 (Apple, MacOS X)
108  - GCC 4.0 (Apple, MacOS X)
110 It has been confirmed not to work with:
112  - GCC 2.95.2 (SunOS 5.8) 
114 Metrowerks 8.3 (Windows) compiles but fails the const-test. This 
115 means that const member functions are treated as non-const member 
116 functions.
118 If you have tried luabind with a compiler not listed here, let us know 
119 your result with it.
121 .. include:: building.rst
123 Basic usage
124 ===========
126 To use luabind, you must include ``lua.h`` and luabind's main header file::
128     extern "C"
129     {
130         #include "lua.h"
131     }
133     #include <luabind/luabind.hpp>
135 This includes support for both registering classes and functions. If you just
136 want to have support for functions or classes you can include
137 ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
139     #include <luabind/function.hpp>
140     #include <luabind/class.hpp>
142 The first thing you need to do is to call ``luabind::open(lua_State*)`` which
143 will register the functions to create classes from Lua, and initialize some
144 state-global structures used by luabind. If you don't call this function you
145 will hit asserts later in the library. There is no corresponding close function
146 because once a class has been registered in Lua, there really isn't any good
147 way to remove it. Partly because any remaining instances of that class relies
148 on the class being there. Everything will be cleaned up when the state is
149 closed though.
151 .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
153 Luabind's headers will never include ``lua.h`` directly, but through
154 ``<luabind/lua_include.hpp>``. If you for some reason need to include another
155 Lua header, you can modify this file.
158 Hello world
159 -----------
163     #include <iostream>
164     #include <luabind/luabind.hpp>
166     void greet()
167     {
168         std::cout << "hello world!\n";
169     }
171     extern "C" int init(lua_State* L)
172     {
173         using namespace luabind;
175         open(L);
177         module(L)
178         [
179             def("greet", &greet)
180         ];
182         return 0;
183     }
187     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
188     > loadlib('hello_world.dll', 'init')()
189     > greet()
190     Hello world!
191     >
193 Scopes
194 ======
196 Everything that gets registered in Lua is registered in a namespace (Lua
197 tables) or in the global scope (called module). All registrations must be
198 surrounded by its scope. To define a module, the ``luabind::module`` class is
199 used. It is used like this::
201     module(L)
202     [
203         // declarations
204     ];
206 This will register all declared functions or classes in the global namespace in
207 Lua. If you want to have a namespace for your module (like the standard
208 libraries) you can give a name to the constructor, like this::
210     module(L, "my_library")
211     [
212         // declarations
213     ];
215 Here all declarations will be put in the my_library table.
217 If you want nested namespace's you can use the ``luabind::namespace_`` class. It
218 works exactly as ``luabind::module`` except that it doesn't take a lua_State*
219 in it's constructor. An example of its usage could look like this::
221     module(L, "my_library")
222     [
223         // declarations
225         namespace_("detail")
226         [
227             // library-private declarations
228         ]
229     ];
231 As you might have figured out, the following declarations are equivalent::
233     module(L)
234     [
235         namespace_("my_library")
236         [
237             // declarations
238         ]
240     ];
243     
244     module(L, "my_library")
245     [
246         // declarations
247     ];
249 Each declaration must be separated by a comma, like this::
251     module(L)
252     [
253         def("f", &f),
254         def("g", &g),
255         class_<A>("A")
256             .def(constructor<int, int>),
257         def("h", &h)
258     ];
261 More about the actual declarations in the `Binding functions to Lua`_ and
262 `Binding classes to Lua`_ sections.
264 A word of caution, if you are in really bad need for performance, putting your
265 functions in tables will increase the lookup time.
268 Binding functions to Lua
269 ========================
271 To bind functions to Lua you use the function ``luabind::def()``. It has the
272 following synopsis::
274     template<class F, class policies>
275     void def(const char* name, F f, const Policies&);
277 - name is the name the function will have within Lua. 
278 - F is the function pointer you want to register. 
279 - The Policies parameter is used to describe how parameters and return values 
280   are treated by the function, this is an optional parameter. More on this in 
281   the `policies`_ section.
283 An example usage could be if you want to register the function ``float
284 std::sin(float)``::
286     module(L)
287     [
288         def("sin", &std::sin)
289     ];
291 Overloaded functions
292 --------------------
294 If you have more than one function with the same name, and want to register
295 them in Lua, you have to explicitly give the signature. This is to let C++ know
296 which function you refer to. For example, if you have two functions, ``int
297 f(const char*)`` and ``void f(int)``. ::
299     module(L)
300     [
301         def("f", (int(*)(const char*)) &f),
302         def("f", (void(*)(int)) &f)
303     ];
305 Signature matching
306 ------------------
308 luabind will generate code that checks the Lua stack to see if the values there
309 can match your functions' signatures. It will handle implicit typecasts between
310 derived classes, and it will prefer matches with the least number of implicit
311 casts. In a function call, if the function is overloaded and there's no
312 overload that match the parameters better than the other, you have an
313 ambiguity. This will spawn a run-time error, stating that the function call is
314 ambiguous. A simple example of this is to register one function that takes an
315 int and one that takes a float. Since Lua doesn't distinguish between floats and
316 integers, both will always match.
318 Since all overloads are tested, it will always find the best match (not the
319 first match). This also means that it can handle situations where the only
320 difference in the signature is that one member function is const and the other
321 isn't. 
323 .. sidebar:: Ownership transfer
325    To correctly handle ownership transfer, create_a() would need an adopt
326    return value policy. More on this in the `Policies`_ section.
328 For example, if the following function and class is registered:
331    
332     struct A
333     {
334         void f();
335         void f() const;
336     };
338     const A* create_a();
340     struct B: A {};
341     struct C: B {};
343     void g(A*);
344     void g(B*);
346 And the following Lua code is executed::
348     a1 = create_a()
349     a1:f() -- the const version is called
351     a2 = A()
352     a2:f() -- the non-const version is called
354     a = A()
355     b = B()
356     c = C()
358     g(a) -- calls g(A*)
359     g(b) -- calls g(B*)
360     g(c) -- calls g(B*)
363 Calling Lua functions
364 ---------------------
366 To call a Lua function, you can either use ``call_function()`` or
367 an ``object``.
371     template<class Ret>
372     Ret call_function(lua_State* L, const char* name, ...)
373     template<class Ret>
374     Ret call_function(object const& obj, ...)
376 There are two overloads of the ``call_function`` function, one that calls
377 a function given its name, and one that takes an object that should be a Lua
378 value that can be called as a function.
380 The overload that takes a name can only call global Lua functions. The ...
381 represents a variable number of parameters that are sent to the Lua
382 function. This function call may throw ``luabind::error`` if the function
383 call fails.
385 The return value isn't actually Ret (the template parameter), but a proxy
386 object that will do the function call. This enables you to give policies to the
387 call. You do this with the operator[]. You give the policies within the
388 brackets, like this::
390     int ret = call_function<int>(
391         L 
392       , "a_lua_function"
393       , new complex_class()
394     )[ adopt(_1) ];
396 If you want to pass a parameter as a reference, you have to wrap it with the
397 `Boost.Ref`__.
399 __ http://www.boost.org/doc/html/ref.html
401 Like this::
403         int ret = call_function(L, "fun", boost::ref(val));
406 If you want to use a custom error handler for the function call, see
407 ``set_pcall_callback`` under `pcall errorfunc`_.
409 Using Lua threads
410 -----------------
412 To start a Lua thread, you have to call ``lua_resume()``, this means that you
413 cannot use the previous function ``call_function()`` to start a thread. You have
414 to use
418     template<class Ret>
419     Ret resume_function(lua_State* L, const char* name, ...)
420     template<class Ret>
421     Ret resume_function(object const& obj, ...)
427     template<class Ret>
428     Ret resume(lua_State* L, ...)
430 The first time you start the thread, you have to give it a function to execute. i.e. you
431 have to use ``resume_function``, when the Lua function yields, it will return the first
432 value passed in to ``lua_yield()``. When you want to continue the execution, you just call
433 ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
434 it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side.
436 For yielding C++-functions (without the support of passing data back and forth between the
437 Lua side and the c++ side), you can use the yield_ policy.
439 With the overload of ``resume_function`` that takes an object_, it is important that the
440 object was constructed with the thread as its ``lua_State*``. Like this:
442 .. parsed-literal::
444         lua_State* thread = lua_newthread(L);
445         object fun = get_global(**thread**)["my_thread_fun"];
446         resume_function(fun);
449 Binding classes to Lua
450 ======================
452 To register classes you use a class called ``class_``. Its name is supposed to
453 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
454 member function ``def()`` that is used to register member functions, operators,
455 constructors, enums and properties on the class. It will return its
456 this-pointer, to let you register more members directly.
458 Let's start with a simple example. Consider the following C++ class::
460     class testclass
461     {
462     public:
463         testclass(const std::string& s): m_string(s) {}
464         void print_string() { std::cout << m_string << "\n"; }
466     private:
467         std::string m_string;
468     };
470 To register it with a Lua environment, write as follows (assuming you are using
471 namespace luabind)::
473     module(L)
474     [
475         class_<testclass>("testclass")
476             .def(constructor<const std::string&>())
477             .def("print_string", &testclass::print_string)
478     ];
480 This will register the class with the name testclass and constructor that takes
481 a string as argument and one member function with the name ``print_string``.
485     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
486     > a = testclass('a string')
487     > a:print_string()
488     a string
490 It is also possible to register free functions as member functions. The
491 requirement on the function is that it takes a pointer, const pointer,
492 reference or const reference to the class type as the first parameter. The rest
493 of the parameters are the ones that are visible in Lua, while the object
494 pointer is given as the first parameter. If we have the following C++ code::
496     struct A
497     {
498         int a;
499     };
501     int plus(A* o, int v) { return o->a + v; }
503 You can register ``plus()`` as if it was a member function of A like this::
505     class_<A>("A")
506         .def("plus", &plus)
508 ``plus()`` can now be called as a member function on A with one parameter, int.
509 If the object pointer parameter is const, the function will act as if it was a
510 const member function (it can be called on const objects).
513 Overloaded member functions
514 ---------------------------
516 When binding more than one overloads of a member function, or just binding
517 one overload of an overloaded member function, you have to disambiguate
518 the member function pointer you pass to ``def``. To do this, you can use an
519 ordinary C-style cast, to cast it to the right overload. To do this, you have
520 to know how to express member function types in C++, here's a short tutorial
521 (for more info, refer to your favourite book on C++).
523 The syntax for member function pointer follows:
525 .. parsed-literal::
527     *return-value* (*class-name*::\*)(*arg1-type*, *arg2-type*, *...*)
529 Here's an example illlustrating this::
531     struct A
532     {
533         void f(int);
534         void f(int, int);
535     };
539     class_<A>()
540         .def("f", (void(A::*)(int))&A::f)
542 This selects the first overload of the function ``f`` to bind. The second
543 overload is not bound.
546 Properties
547 ----------
549 To register a global data member with a class is easily done. Consider the
550 following class::
552     struct A
553     {
554         int a;
555     };
557 This class is registered like this::
559     module(L)
560     [
561         class_<A>("A")
562             .def_readwrite("a", &A::a)
563     ];
565 This gives read and write access to the member variable ``A::a``. It is also
566 possible to register attributes with read-only access::
568     module(L)
569     [
570         class_<A>("A")
571             .def_readonly("a", &A::a)
572     ];
574 When binding members that are a non-primitive type, the auto generated getter
575 function will return a reference to it. This is to allow chained .-operators.
576 For example, when having a struct containing another struct. Like this::
578     struct A { int m; };
579     struct B { A a; };
581 When binding ``B`` to lua, the following expression code should work::
583     b = B()
584     b.a.m = 1
585     assert(b.a.m == 1)
587 This requires the first lookup (on ``a``) to return a reference to ``A``, and
588 not a copy. In that case, luabind will automatically use the dependency policy
589 to make the return value dependent on the object in which it is stored. So, if
590 the returned reference lives longer than all references to the object (b in
591 this case) it will keep the object alive, to avoid being a dangling pointer.
593 You can also register getter and setter functions and make them look as if they
594 were a public data member. Consider the following class::
596     class A
597     {
598     public:
599         void set_a(int x) { a = x; }
600         int get_a() const { return a; }
602     private:
603         int a;
604     };
606 It can be registered as if it had a public data member a like this::
608     class_<A>("A")
609         .property("a", &A::get_a, &A::set_a)
611 This way the ``get_a()`` and ``set_a()`` functions will be called instead of
612 just writing  to the data member. If you want to make it read only you can just
613 omit the last parameter. Please note that the get function **has to be
614 const**, otherwise it won't compile. This seems to be a common source of errors.
617 Enums
618 -----
620 If your class contains enumerated constants (enums), you can register them as
621 well to make them available in Lua. Note that they will not be type safe, all
622 enums are integers in Lua, and all functions that takes an enum, will accept
623 any integer. You register them like this::
625     module(L)
626     [
627         class_<A>("A")
628             .enum_("constants")
629             [
630                 value("my_enum", 4),
631                 value("my_2nd_enum", 7),
632                 value("another_enum", 6)
633             ]
634     ];
636 In Lua they are accessed like any data member, except that they are read-only
637 and reached on the class itself rather than on an instance of the class.
641     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
642     > print(A.my_enum)
643     4
644     > print(A.another_enum)
645     6
648 Operators
649 ---------
651 To bind operators you have to include ``<luabind/operator.hpp>``.
653 The mechanism for registering operators on your class is pretty simple. You use
654 a global name ``luabind::self`` to refer to the class itself and then you just
655 write the operator expression inside the ``def()`` call. This class::
657     struct vec
658     {
659         vec operator+(int s);
660     };
662 Is registered like this:
664 .. parsed-literal::
666     module(L)
667     [
668         class_<vec>("vec")
669             .def(**self + int()**)
670     ];
672 This will work regardless if your plus operator is defined inside your class or
673 as a free function.
675 If your operator is const (or, when defined as a free function, takes a const
676 reference to the class itself) you have to use ``const_self`` instead of
677 ``self``. Like this:
679 .. parsed-literal::
681     module(L)
682     [
683         class_<vec>("vec")
684             .def(**const_self** + int())
685     ];
687 The operators supported are those available in Lua:
689 .. parsed-literal::
691     +    -    \*    /    ==    <    <=
693 This means, no in-place operators. The equality operator (``==``) has a little
694 hitch; it will not be called if the references are equal. This means that the
695 ``==`` operator has to do pretty much what's it's expected to do.
697 Lua does not support operators such as ``!=``, ``>`` or ``>=``. That's why you
698 can only register the operators listed above. When you invoke one of the
699 mentioned operators, lua will define it in terms of one of the avaliable
700 operators.
702 In the above example the other operand type is instantiated by writing
703 ``int()``. If the operand type is a complex type that cannot easily be
704 instantiated you can wrap the type in a class called ``other<>``. For example:
706 To register this class, we don't want to instantiate a string just to register
707 the operator.
711     struct vec
712     {
713         vec operator+(std::string);
714     };
716 Instead we use the ``other<>`` wrapper like this:
718 .. parsed-literal::
720     module(L)
721     [
722         class_<vec>("vec")
723             .def(self + **other<std::string>()**)
724     ];
726 To register an application (function call-) operator:
728 .. parsed-literal::
730     module(L)
731     [
732         class_<vec>("vec")
733             .def( **self(int())** )
734     ];
736 There's one special operator. In Lua it's called ``__tostring``, it's not
737 really an operator. It is used for converting objects to strings in a standard
738 way in Lua. If you register this functionality, you will be able to use the lua
739 standard function ``tostring()`` for converting your object to a string.
741 To implement this operator in C++ you should supply an ``operator<<`` for
742 std::ostream. Like this example:
744 .. parsed-literal::
746     class number {};
747     std::ostream& operator<<(std::ostream&, number&);
749     ...
750     
751     module(L)
752     [
753         class_<number>("number")
754             .def(**tostring(self)**)
755     ];
758 Nested scopes and static functions
759 ----------------------------------
761 It is possible to add nested scopes to a class. This is useful when you need 
762 to wrap a nested class, or a static function.
764 .. parsed-literal::
766     class_<foo>("foo")
767         .def(constructor<>())
768         **.scope
769         [
770             class_<inner>("nested"),
771             def("f", &f)
772         ]**;
774 In this example, ``f`` will behave like a static member function of the class
775 ``foo``, and the class ``nested`` will behave like a nested class of ``foo``.
777 It's also possible to add namespace's to classes using the same syntax.
780 Derived classes
781 ---------------
782   
783 If you want to register classes that derives from other classes, you can
784 specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
785 following hierarchy::
786    
787     struct A {};
788     struct B : A {};
790 Would be registered like this::
792     module(L)
793     [
794         class_<A>("A"),
795         class_<B, A>("B")
796     ];
798 If you have multiple inheritance you can specify more than one base. If B would
799 also derive from a class C, it would be registered like this::
801     module(L)
802     [
803         class_<B, bases<A, C> >("B")
804     ];
806 Note that you can omit ``bases<>`` when using single inheritance.
808 .. note::
809    If you don't specify that classes derive from each other, luabind will not
810    be able to implicitly cast pointers between the types.
813 Smart pointers
814 --------------
816 When you register a class you can tell luabind that all instances of that class
817 should be held by some kind of smart pointer (boost::shared_ptr for instance).
818 You do this by giving the holder type as an extra template parameter to
819 the ``class_`` you are constructing, like this::
821     module(L)
822     [
823         class_<A, boost::shared_ptr<A> >("A")
824     ];
826 You also have to supply two functions for your smart pointer. One that returns
827 the type of const version of the smart pointer type (boost::shared_ptr<const A>
828 in this case). And one function that extracts the raw pointer from the smart
829 pointer. The first function is needed because luabind has to allow the
830 non-const -> conversion when passing values from Lua to C++. The second
831 function is needed when Lua calls member functions on held types, the this
832 pointer must be a raw pointer, it is also needed to allow the smart_pointer ->
833 raw_pointer conversion from Lua to C++. They look like this::
835     namespace luabind {
837         template<class T>
838         T* get_pointer(boost::shared_ptr<T>& p) 
839         {
840             return p.get(); 
841         }
843         template<class A>
844         boost::shared_ptr<const A>* 
845         get_const_holder(boost::shared_ptr<A>*)
846         {
847             return 0;
848         }
849     }
851 The second function will only be used to get a compile time mapping
852 of ``boost::shared_ptr<A>`` to its const version,
853 ``boost::shared_ptr<const A>``. It will never be called, so the
854 return value doesn't matter (only the return type).
856 The conversion that works are (given that B is a base class of A):
858 .. topic:: From Lua to C++
860     ========================= ========================
861     Source                    Target
862     ========================= ========================
863     ``holder_type<A>``        ``A*``
864     ``holder_type<A>``        ``B*``
865     ``holder_type<A>``        ``A const*``
866     ``holder_type<A>``        ``B const*``
867     ``holder_type<A>``        ``holder_type<A>``
868     ``holder_type<A>``        ``holder_type<A const>``
869     ``holder_type<A const>``  ``A const*``
870     ``holder_type<A const>``  ``B const*``
871     ``holder_type<A const>``  ``holder_type<A const>``
872     ========================= ========================
874 .. topic:: From C++ to Lua
876     =============================== ========================
877     Source                          Target
878     =============================== ========================
879     ``holder_type<A>``              ``holder_type<A>``
880     ``holder_type<A const>``        ``holder_type<A const>``
881     ``holder_type<A> const&``       ``holder_type<A>``
882     ``holder_type<A const> const&`` ``holder_type<A const>``
883     =============================== ========================
885 When using a holder type, it can be useful to know if the pointer is valid
886 (i.e. not null). For example when using std::auto_ptr, the holder will be
887 invalidated when passed as a parameter to a function. For this purpose there
888 is a member of all object instances in luabind: ``__ok``. ::
890     struct X {};
891     void f(std::auto_ptr<X>);
893     module(L)
894     [
895         class_<X, std::auto_ptr<X> >("X")
896             .def(constructor<>()),
898         def("f", &f)
899     ];
902     
903     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
904     > a = X()
905     > f(a)
906     > print a.__ok
907     false
910 When registering a hierarchy of classes, where all instances are to be held
911 by a smart pointer, all the classes should have the baseclass' holder type.
912 Like this:
914 .. parsed-literal::
916         module(L)
917         [
918             class_<base, boost::shared_ptr<base> >("base")
919                 .def(constructor<>()),
920             class_<derived, base, **boost::shared_ptr<base>** >("base")
921                 .def(constructor<>())
922         ];
924 Internally, luabind will do the necessary conversions on the raw pointers, which
925 are first extracted from the holder type.
928 Splitting class registrations
929 -----------------------------
931 In some situations it may be desirable to split a registration of a class
932 across different compilation units. Partly to save rebuild time when changing
933 in one part of the binding, and in some cases compiler limits may force you
934 to split it. To do this is very simple. Consider the following sample code::
936     void register_part1(class_<X>& x)
937     {
938         x.def(/*...*/);
939     }
941     void register_part2(class_<X>& x)
942     {
943         x.def(/*...*/);
944     }
946     void register_(lua_State* L)
947     {
948         class_<X> x("x");
950         register_part1(x);
951         register_part2(x);
953         module(L) [ x ];
954     }
956 Here, the class ``X`` is registered in two steps. The two functions
957 ``register_part1`` and ``register_part2`` may be put in separate compilation
958 units.
960 To separate the module registration and the classes to be registered, see
961 `Splitting up the registration`_.
964 Adding converters for user defined types
965 ========================================
967 It is possible to get luabind to handle user defined types like it does
968 the built in types by specializing ``luabind::default_converter<>``:
972   struct int_wrapper
973   {
974       int_wrapper(int value)
975         : value(value)
976       {}
978       int value;
979   };
981   namespace luabind
982   {
983       template <>
984       struct default_converter<X>
985         : native_converter_base<X>
986       {
987           static int compute_score(lua_State* L, int index)
988           {
989               return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;
990           }
992           X from(lua_State* L, int index)
993           {
994               return X(lua_tonumber(L, index));
995           }
997           void to(lua_State* L, X const& x)
998           {
999               lua_pushnumber(L, x.value);
1000           }
1001       };
1003       template <>
1004       struct default_converter<X const&>
1005         : default_converter<X>
1006       {};
1007   }
1009 Note that ``default_converter<>`` is instantiated for the actual argument and
1010 return types of the bound functions. In the above example, we add a
1011 specialization for ``X const&`` that simply forwards to the ``X`` converter.
1012 This lets us export functions which accept ``X`` by const reference.
1014 ``native_converter_base<>`` should be used as the base class for the
1015 specialized converters. It simplifies the converter interface, and
1016 provides a mean for backward compatibility since the underlying
1017 interface is in flux.
1020 Binding function objects with explicit signatures
1021 =================================================
1023 Using ``luabind::tag_function<>`` it is possible to export function objects
1024 from which luabind can't automatically deduce a signature. This can be used to
1025 slightly alter the signature of a bound function, or even to bind stateful
1026 function objects.
1028 Synopsis:
1030 .. parsed-literal::
1032   template <class Signature, class F>
1033   *implementation-defined* tag_function(F f);
1035 Where ``Signature`` is a function type describing the signature of ``F``.
1036 It can be used like this::
1038   int f(int x);
1040   // alter the signature so that the return value is ignored
1041   def("f", tag_function<void(int)>(f));
1043   struct plus
1044   {
1045       plus(int x)
1046         : x(x)
1047       {}
1049       int operator()(int y) const
1050       {
1051           return x + y;
1052       }
1053   };
1055   // bind a stateful function object
1056   def("plus3", tag_function<int(int)>(plus(3)));
1059 Object
1060 ======
1062 Since functions have to be able to take Lua values (of variable type) we need a
1063 wrapper around them. This wrapper is called ``luabind::object``. If the
1064 function you register takes an object, it will match any Lua value. To use it,
1065 you need to include ``<luabind/object.hpp>``.
1067 .. topic:: Synopsis
1069     .. parsed-literal::
1071         class object
1072         {
1073         public:
1074             template<class T>
1075             object(lua_State\*, T const& value);
1076             object(from_stack const&);
1077             object(object const&);
1078             object();
1080             ~object();
1082             lua_State\* interpreter() const;
1083             void push() const;
1084             bool is_valid() const;
1085             operator *safe_bool_type* () const;
1087             template<class Key>
1088             *implementation-defined* operator[](Key const&);
1090             template<class T>
1091             object& operator=(T const&);
1092             object& operator=(object const&);
1094             bool operator==(object const&) const;
1095             bool operator<(object const&) const;
1096             bool operator<=(object const&) const;
1097             bool operator>(object const&) const;
1098             bool operator>=(object const&) const;
1099             bool operator!=(object const&) const;
1101             template <class T>
1102             *implementation-defined* operator[](T const& key) const
1104             void swap(object&);
1106             *implementation-defined* operator()();
1108             template<class A0>
1109             *implementation-defined* operator()(A0 const& a0);
1111             template<class A0, class A1>
1112             *implementation-defined* operator()(A0 const& a0, A1 const& a1);
1114             /\* ... \*/
1115         };
1117 When you have a Lua object, you can assign it a new value with the assignment
1118 operator (=). When you do this, the ``default_policy`` will be used to make the
1119 conversion from C++ value to Lua. If your ``luabind::object`` is a table you
1120 can access its members through the operator[] or the Iterators_. The value
1121 returned from the operator[] is a proxy object that can be used both for
1122 reading and writing values into the table (using operator=).
1124 Note that it is impossible to know if a Lua value is indexable or not
1125 (``lua_gettable`` doesn't fail, it succeeds or crashes). This means that if
1126 you're trying to index something that cannot be indexed, you're on your own.
1127 Lua will call its ``panic()`` function. See `lua panic`_.
1129 There are also free functions that can be used for indexing the table, see
1130 `Related functions`_.
1132 The constructor that takes a ``from_stack`` object is used when you want to
1133 initialize the object with a value from the lua stack. The ``from_stack``
1134 type has the following constructor::
1136          from_stack(lua_State* L, int index);
1138 The index is an ordinary lua stack index, negative values are indexed from the
1139 top of the stack. You use it like this::
1141          object o(from_stack(L, -1));
1143 This will create the object ``o`` and copy the value from the top of the lua stack.
1145 The ``interpreter()`` function returns the Lua state where this object is stored.
1146 If you want to manipulate the object with Lua functions directly you can push
1147 it onto the Lua stack by calling ``push()``.
1149 The operator== will call lua_equal() on the operands and return its result.
1151 The ``is_valid()`` function tells you whether the object has been initialized
1152 or not. When created with its default constructor, objects are invalid. To make
1153 an object valid, you can assign it a value. If you want to invalidate an object
1154 you can simply assign it an invalid object.
1156 The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
1157 that these snippets are equivalent::
1159     object o;
1160     // ...
1161     if (o)
1162     {
1163         // ...
1164     }
1166     ...
1168     object o;
1169     // ...
1170     if (o.is_valid())
1171     {
1172         // ...
1173     }
1175 The application operator will call the value as if it was a function. You can
1176 give it any number of parameters (currently the ``default_policy`` will be used
1177 for the conversion). The returned object refers to the return value (currently
1178 only one return value is supported). This operator may throw ``luabind::error``
1179 if the function call fails. If you want to specify policies to your function
1180 call, you can use index-operator (operator[]) on the function call, and give
1181 the policies within the [ and ]. Like this::
1183     my_function_object(
1184         2
1185       , 8
1186       , new my_complex_structure(6)
1187     ) [ adopt(_3) ];
1189 This tells luabind to make Lua adopt the ownership and responsibility for the
1190 pointer passed in to the lua-function.
1192 It's important that all instances of object have been destructed by the time
1193 the Lua state is closed. The object will keep a pointer to the lua state and
1194 release its Lua object in its destructor.
1196 Here's an example of how a function can use a table::
1198     void my_function(object const& table)
1199     {
1200         if (type(table) == LUA_TTABLE)
1201         {
1202             table["time"] = std::clock();
1203             table["name"] = std::rand() < 500 ? "unusual" : "usual";
1205             std::cout << object_cast<std::string>(table[5]) << "\n";
1206         }
1207     }
1209 If you take a ``luabind::object`` as a parameter to a function, any Lua value
1210 will match that parameter. That's why we have to make sure it's a table before
1211 we index into it.
1215     std::ostream& operator<<(std::ostream&, object const&);
1217 There's a stream operator that makes it possible to print objects or use
1218 ``boost::lexical_cast`` to convert it to a string. This will use lua's string
1219 conversion function. So if you convert a C++ object with a ``tostring``
1220 operator, the stream operator for that type will be used.
1222 Iterators
1223 ---------
1225 There are two kinds of iterators. The normal iterator that will use the metamethod
1226 of the object (if there is any) when the value is retrieved. This iterator is simply
1227 called ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator``
1228 and will bypass the metamethod and give the true contents of the table. They have
1229 identical interfaces, which implements the ForwardIterator_ concept. Apart from
1230 the members of standard iterators, they have the following members and constructors:
1232 .. _ForwardIterator: http://www.sgi.com/tech/stl/ForwardIterator.html
1234 .. parsed-literal::
1236     class iterator
1237     {
1238         iterator();
1239         iterator(object const&);
1241         object key() const;
1243         *standard iterator members*
1244     };
1246 The constructor that takes a ``luabind::object`` is actually a template that can be
1247 used with object. Passing an object as the parameter to the iterator will
1248 construct the iterator to refer to the first element in the object.
1250 The default constructor will initialize the iterator to the one-past-end
1251 iterator. This is used to test for the end of the sequence.
1253 The value type of the iterator is an implementation defined proxy type which
1254 supports the same operations as ``luabind::object``. Which means that in most
1255 cases you can just treat it as an ordinary object. The difference is that any
1256 assignments to this proxy will result in the value being inserted at the
1257 iterators position, in the table.
1259 The ``key()`` member returns the key used by the iterator when indexing the
1260 associated Lua table.
1262 An example using iterators::
1264     for (iterator i(globals(L)["a"]), end; i != end; ++i)
1265     {
1266       *i = 1;
1267     }
1269 The iterator named ``end`` will be constructed using the default constructor
1270 and hence refer to the end of the sequence. This example will simply iterate
1271 over the entries in the global table ``a`` and set all its values to 1.
1273 Related functions
1274 -----------------
1276 There are a couple of functions related to objects and tables.
1280     int type(object const&);
1282 This function will return the lua type index of the given object.
1283 i.e. ``LUA_TNIL``, ``LUA_TNUMBER`` etc.
1287     template<class T, class K>
1288     void settable(object const& o, K const& key, T const& value);
1289     template<class K>
1290     object gettable(object const& o, K const& key);
1291     template<class T, class K>
1292     void rawset(object const& o, K const& key, T const& value);
1293     template<class K>
1294     object rawget(object const& o, K const& key);
1296 These functions are used for indexing into tables. ``settable`` and ``gettable``
1297 translates into calls to ``lua_settable`` and ``lua_gettable`` respectively. Which
1298 means that you could just as well use the index operator of the object.
1300 ``rawset`` and ``rawget`` will translate into calls to ``lua_rawset`` and
1301 ``lua_rawget`` respectively. So they will bypass any metamethod and give you the
1302 true value of the table entry.
1306     template<class T>
1307     T object_cast<T>(object const&);
1308     template<class T, class Policies>
1309     T object_cast<T>(object const&, Policies);
1311     template<class T>
1312     boost::optional<T> object_cast_nothrow<T>(object const&);
1313     template<class T, class Policies>
1314     boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
1316 The ``object_cast`` function casts the value of an object to a C++ value.
1317 You can supply a policy to handle the conversion from lua to C++. If the cast
1318 cannot be made a ``cast_failed`` exception will be thrown. If you have
1319 defined LUABIND_NO_ERROR_CHECKING (see `Build options`_) no checking will occur,
1320 and if the cast is invalid the application may very well crash. The nothrow
1321 versions will return an uninitialized ``boost::optional<T>`` object, to
1322 indicate that the cast could not be performed.
1324 The function signatures of all of the above functions are really templates
1325 for the object parameter, but the intention is that you should only pass
1326 objects in there, that's why it's left out of the documentation.
1330     object globals(lua_State*);
1331     object registry(lua_State*);
1333 These functions return the global environment table and the registry table respectively.
1337   object newtable(lua_State*);
1339 This function creates a new table and returns it as an object.
1343   object getmetatable(object const& obj);
1344   void setmetatable(object const& obj, object const& metatable);
1346 These functions get and set the metatable of a Lua object.
1350   lua_CFunction tocfunction(object const& value);
1351   template <class T> T* touserdata(object const& value)
1353 These extract values from the object at a lower level than ``object_cast()``.
1357   object getupvalue(object const& function, int index);
1358   void setupvalue(object const& function, int index, object const& value);
1360 These get and set the upvalues of ``function``.
1362 Assigning nil
1363 -------------
1365 To set a table entry to ``nil``, you can use ``luabind::nil``. It will avoid
1366 having to take the detour by first assigning ``nil`` to an object and then
1367 assign that to the table entry. It will simply result in a ``lua_pushnil()``
1368 call, instead of copying an object.
1370 Example::
1372   using luabind;
1373   object table = newtable(L);
1374   table["foo"] = "bar";
1375   
1376   // now, clear the "foo"-field
1377   table["foo"] = nil;
1380 Defining classes in Lua
1381 =======================
1383 In addition to binding C++ functions and classes with Lua, luabind also provide
1384 an OO-system in Lua. ::
1386     class 'lua_testclass'
1388     function lua_testclass:__init(name)
1389         self.name = name
1390     end
1392     function lua_testclass:print()
1393         print(self.name)
1394     end
1396     a = lua_testclass('example')
1397     a:print()
1400 Inheritance can be used between lua-classes::
1402     class 'derived' (lua_testclass)
1404     function derived:__init()
1405         lua_testclass.__init(self, 'derived name')
1406     end
1408     function derived:print()
1409         print('Derived:print() -> ')
1410         lua_testclass.print(self)
1411     end
1413 The base class is initialized explicitly by calling its ``__init()``
1414 function.
1416 As you can see in this example, you can call the base class member functions.
1417 You can find all member functions in the base class, but you will have to give
1418 the this-pointer (``self``) as first argument.
1421 Deriving in lua
1422 ---------------
1424 It is also possible to derive Lua classes from C++ classes, and override
1425 virtual functions with Lua functions. To do this we have to create a wrapper
1426 class for our C++ base class. This is the class that will hold the Lua object
1427 when we instantiate a Lua class.
1431     class base
1432     {
1433     public:
1434         base(const char* s)
1435         { std::cout << s << "\n"; }
1437         virtual void f(int a) 
1438         { std::cout << "f(" << a << ")\n"; }
1439     };
1441     struct base_wrapper : base, luabind::wrap_base
1442     {
1443         base_wrapper(const char* s)
1444             : base(s) 
1445         {}
1447         virtual void f(int a) 
1448         { 
1449             call<void>("f", a); 
1450         }
1452         static void default_f(base* ptr, int a)
1453         {
1454             return ptr->base::f(a);
1455         }
1456     };
1458     ...
1460     module(L)
1461     [
1462         class_<base, base_wrapper>("base")
1463             .def(constructor<const char*>())
1464             .def("f", &base::f, &base_wrapper::default_f)
1465     ];
1467 .. Important::
1468     Since MSVC6.5 doesn't support explicit template parameters
1469     to member functions, instead of using the member function ``call()``
1470     you call a free function ``call_member()`` and pass the this-pointer
1471     as first parameter.
1473 Note that if you have both base classes and a base class wrapper, you must give
1474 both bases and the base class wrapper type as template parameter to 
1475 ``class_`` (as done in the example above). The order in which you specify
1476 them is not important. You must also register both the static version and the
1477 virtual version of the function from the wrapper, this is necessary in order
1478 to allow luabind to use both dynamic and static dispatch when calling the function.
1480 .. Important::
1481     It is extremely important that the signatures of the static (default) function
1482     is identical to the virtual function. The fact that one of them is a free
1483     function and the other a member function doesn't matter, but the parameters
1484     as seen from lua must match. It would not have worked if the static function
1485     took a ``base_wrapper*`` as its first argument, since the virtual function
1486     takes a ``base*`` as its first argument (its this pointer). There's currently
1487     no check in luabind to make sure the signatures match.
1489 If we didn't have a class wrapper, it would not be possible to pass a Lua class
1490 back to C++. Since the entry points of the virtual functions would still point
1491 to the C++ base class, and not to the functions defined in Lua. That's why we
1492 need one function that calls the base class' real function (used if the lua
1493 class doesn't redefine it) and one virtual function that dispatches the call
1494 into luabind, to allow it to select if a Lua function should be called, or if
1495 the original function should be called. If you don't intend to derive from a
1496 C++ class, or if it doesn't have any virtual member functions, you can register
1497 it without a class wrapper.
1499 You don't need to have a class wrapper in order to derive from a class, but if
1500 it has virtual functions you may have silent errors. 
1502 .. Unnecessary? The rule of thumb is: 
1503   If your class has virtual functions, create a wrapper type, if it doesn't
1504   don't create a wrapper type.
1506 The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference
1507 that will hold the Lua instance of the object to make it possible to dispatch
1508 virtual function calls into Lua. This is done through an overloaded member function::
1510     template<class Ret>
1511     Ret call(char const* name, ...)
1513 Its used in a similar way as ``call_function``, with the exception that it doesn't
1514 take a ``lua_State`` pointer, and the name is a member function in the Lua class.
1516 .. warning::
1518         The current implementation of ``call_member`` is not able to distinguish const
1519         member functions from non-const. If you have a situation where you have an overloaded
1520         virtual function where the only difference in their signatures is their constness, the
1521         wrong overload will be called by ``call_member``. This is rarely the case though.
1523 Object identity
1524 ~~~~~~~~~~~~~~~
1526 When a pointer or reference to a registered class with a wrapper is passed
1527 to Lua, luabind will query for it's dynamic type. If the dynamic type
1528 inherits from ``wrap_base``, object identity is preserved.
1532     struct A { .. };
1533     struct A_wrap : A, wrap_base { .. };
1535     A* f(A* ptr) { return ptr; }
1537     module(L)
1538     [
1539         class_<A, A_wrap>("A"),
1540         def("f", &f)
1541     ];
1545     > class 'B' (A)
1546     > x = B()
1547     > assert(x == f(x)) -- object identity is preserved when object is
1548                         -- passed through C++
1550 This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is
1551 not defined).
1553 Overloading operators
1554 ---------------------
1556 You can overload most operators in Lua for your classes. You do this by simply
1557 declaring a member function with the same name as an operator (the name of the
1558 metamethods in Lua). The operators you can overload are:
1560  - ``__add``
1561  - ``__sub`` 
1562  - ``__mul`` 
1563  - ``__div`` 
1564  - ``__pow`` 
1565  - ``__lt`` 
1566  - ``__le`` 
1567  - ``__eq`` 
1568  - ``__call`` 
1569  - ``__unm`` 
1570  - ``__tostring``
1571  - ``__len``
1573 ``__tostring`` isn't really an operator, but it's the metamethod that is called
1574 by the standard library's ``tostring()`` function. There's one strange behavior
1575 regarding binary operators. You are not guaranteed that the self pointer you
1576 get actually refers to an instance of your class. This is because Lua doesn't
1577 distinguish the two cases where you get the other operand as left hand value or
1578 right hand value. Consider the following examples::
1580     class 'my_class'
1582       function my_class:__init(v)
1583           self.val = v
1584       end
1585         
1586       function my_class:__sub(v)
1587           return my_class(self.val - v.val)
1588       end
1590       function my_class:__tostring()
1591           return self.val
1592       end
1594 This will work well as long as you only subtracts instances of my_class with
1595 each other. But If you want to be able to subtract ordinary numbers from your
1596 class too, you have to manually check the type of both operands, including the
1597 self object. ::
1599     function my_class:__sub(v)
1600         if (type(self) == 'number') then
1601             return my_class(self - v.val)
1603         elseif (type(v) == 'number') then
1604             return my_class(self.val - v)
1605         
1606         else
1607             -- assume both operands are instances of my_class
1608             return my_class(self.val - v.val)
1610         end
1611     end
1613 The reason why ``__sub`` is used as an example is because subtraction is not
1614 commutative (the order of the operands matters). That's why luabind cannot
1615 change order of the operands to make the self reference always refer to the
1616 actual class instance.
1618 If you have two different Lua classes with an overloaded operator, the operator
1619 of the right hand side type will be called. If the other operand is a C++ class
1620 with the same operator overloaded, it will be prioritized over the Lua class'
1621 operator. If none of the C++ overloads matches, the Lua class operator will be
1622 called.
1625 Finalizers
1626 ----------
1628 If an object needs to perform actions when it's collected we provide a
1629 ``__finalize`` function that can be overridden in lua-classes. The
1630 ``__finalize`` functions will be called on all classes in the inheritance
1631 chain, starting with the most derived type. ::
1633     ...
1635     function lua_testclass:__finalize()
1636         -- called when the an object is collected
1637     end
1640 Slicing
1641 -------
1643 If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and
1644 you derive from them in lua, they may be sliced. Meaning, if an object
1645 is passed into C++ as a pointer to its base class, the lua part will be
1646 separated from the C++ base part. This means that if you call virtual
1647 functions on that C++ object, they will not be dispatched to the lua
1648 class. It also means that if you adopt the object, the lua part will be
1649 garbage collected.
1653         +--------------------+
1654         | C++ object         |    <- ownership of this part is transferred
1655         |                    |       to c++ when adopted
1656         +--------------------+
1657         | lua class instance |    <- this part is garbage collected when
1658         | and lua members    |       instance is adopted, since it cannot
1659         +--------------------+       be held by c++. 
1662 The problem can be illustrated by this example::
1664     struct A {};
1666     A* filter_a(A* a) { return a; }
1667     void adopt_a(A* a) { delete a; }
1672     using namespace luabind;
1674     module(L)
1675     [
1676         class_<A>("A"),
1677         def("filter_a", &filter_a),
1678         def("adopt_a", &adopt_a, adopt(_1))
1679     ]
1682 In lua::
1684     a = A()
1685     b = filter_a(a)
1686     adopt_a(b)
1688 In this example, lua cannot know that ``b`` actually is the same object as
1689 ``a``, and it will therefore consider the object to be owned by the C++ side.
1690 When the ``b`` pointer then is adopted, a runtime error will be raised because
1691 an object not owned by lua is being adopted to C++.
1693 If you have a wrapper for your class, none of this will happen, see
1694 `Object identity`_.
1697 Exceptions
1698 ==========
1700 If any of the functions you register throws an exception when called, that
1701 exception will be caught by luabind and converted to an error string and
1702 ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
1703 ``const char*`` the string that is pushed on the Lua stack, as error message,
1704 will be the string returned by ``std::exception::what()`` or the string itself
1705 respectively. If the exception is unknown, a generic string saying that the
1706 function threw an exception will be pushed.
1708 If you have an exception type that isn't derived from
1709 ``std::exception``, or you wish to change the error message from the
1710 default result of ``what()``, it is possible to register custom
1711 exception handlers::
1713   struct my_exception
1714   {};
1716   void translate_my_exception(lua_State* L, my_exception const&)
1717   {
1718       lua_pushstring(L, "my_exception");
1719   }
1721   …
1723   luabind::register_exception_handler<my_exception>(&translate_my_exception);
1725 ``translate_my_exception()`` will be called by luabind whenever a
1726 ``my_exception`` is caught. ``lua_error()`` will be called after the
1727 handler function returns, so it is expected that the function will push
1728 an error string on the stack.
1730 Any function that invokes Lua code may throw ``luabind::error``. This exception
1731 means that a Lua run-time error occurred. The error message is found on top of
1732 the Lua stack. The reason why the exception doesn't contain the error string
1733 itself is because it would then require heap allocation which may fail. If an
1734 exception class throws an exception while it is being thrown itself, the
1735 application will be terminated.
1737 Error's synopsis is::
1739     class error : public std::exception
1740     {
1741     public:
1742         error(lua_State*);
1743         lua_State* state() const throw();
1744         virtual const char* what() const throw();
1745     };
1747 The state function returns a pointer to the Lua state in which the error was
1748 thrown. This pointer may be invalid if you catch this exception after the lua
1749 state is destructed. If the Lua state is valid you can use it to retrieve the
1750 error message from the top of the Lua stack.
1752 An example of where the Lua state pointer may point to an invalid state
1753 follows::
1755     struct lua_state
1756     {
1757         lua_state(lua_State* L): m_L(L) {}
1758         ~lua_state() { lua_close(m_L); }
1759         operator lua_State*() { return m_L; }
1760         lua_State* m_L;
1761     };
1763     int main()
1764     {
1765         try
1766         {
1767             lua_state L = lua_open();
1768             /* ... */
1769         }
1770         catch(luabind::error& e)
1771         {
1772             lua_State* L = e.state();
1773             // L will now point to the destructed
1774             // Lua state and be invalid
1775             /* ... */
1776         }
1777     }
1779 There's another exception that luabind may throw: ``luabind::cast_failed``,
1780 this exception is thrown from ``call_function<>`` or ``call_member<>``. It
1781 means that the return value from the Lua function couldn't be converted to
1782 a C++ value. It is also thrown from ``object_cast<>`` if the cast cannot
1783 be made.
1785 The synopsis for ``luabind::cast_failed`` is::
1787     class cast_failed : public std::exception
1788     {
1789     public:
1790         cast_failed(lua_State*);
1791         lua_State* state() const throw();
1792         LUABIND_TYPE_INFO info() const throw();
1793         virtual const char* what() const throw();
1794     };
1796 Again, the state member function returns a pointer to the Lua state where the
1797 error occurred. See the example above to see where this pointer may be invalid.
1799 The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
1800 defaults to a ``const std::type_info*``. This type info describes the type that
1801 we tried to cast a Lua value to.
1803 If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
1804 thrown, instead you can set two callback functions that are called instead.
1805 These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
1809     luabind::set_error_callback(void(*)(lua_State*))
1811 The function you set will be called when a runtime-error occur in Lua code. You
1812 can find an error message on top of the Lua stack. This function is not
1813 expected to return, if it does luabind will call ``std::terminate()``.
1817     luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1819 The function you set is called instead of throwing ``cast_failed``. This function
1820 is not expected to return, if it does luabind will call ``std::terminate()``.
1823 Policies
1824 ========
1826 Sometimes it is necessary to control how luabind passes arguments and return
1827 value, to do this we have policies. All policies use an index to associate
1828 them with an argument in the function signature. These indices are ``result`` 
1829 and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers
1830 to the ``this`` pointer.
1832 .. contents:: Policies currently implemented
1833     :local:
1834     :depth: 1
1836 .. include:: adopt.rst
1837 .. include:: dependency.rst
1838 .. include:: out_value.rst
1839 .. include:: pure_out_value.rst
1840 .. include:: return_reference_to.rst
1841 .. include:: copy.rst
1842 .. include:: discard_result.rst
1843 .. include:: return_stl_iterator.rst
1844 .. include:: raw.rst
1845 .. include:: yield.rst
1847 ..  old policies section
1848     ===================================================
1850     Copy
1851     ----
1853     This will make a copy of the parameter. This is the default behavior when
1854     passing parameters by-value. Note that this can only be used when passing from
1855     C++ to Lua. This policy requires that the parameter type has a copy
1856     constructor.
1858     To use this policy you need to include ``luabind/copy_policy.hpp``.
1861     Adopt
1862     -----
1864     This will transfer ownership of the parameter.
1866     Consider making a factory function in C++ and exposing it to lua::
1868         base* create_base()
1869         {
1870             return new base();
1871         }
1873         ...
1875         module(L)
1876         [
1877             def("create_base", create_base)
1878         ];
1880     Here we need to make sure Lua understands that it should adopt the pointer
1881     returned by the factory-function. This can be done using the adopt-policy.
1883     ::
1885         module(L)
1886         [
1887             def(L, "create_base", adopt(return_value))
1888         ];
1890     To specify multiple policies we just separate them with '+'.
1892     ::
1894         base* set_and_get_new(base* ptr)
1895         {
1896             base_ptrs.push_back(ptr);
1897             return new base();
1898         }
1900         module(L)
1901         [
1902             def("set_and_get_new", &set_and_get_new, 
1903                 adopt(return_value) + adopt(_1))
1904         ];
1906     When Lua adopts a pointer, it will call delete on it. This means that it cannot
1907     adopt pointers allocated with another allocator than new (no malloc for
1908     example).
1910     To use this policy you need to include ``luabind/adopt_policy.hpp``.
1913     Dependency
1914     ----------
1916     The dependency policy is used to create life-time dependencies between values.
1917     Consider the following example::
1919         struct A
1920         {
1921             B member;
1923             const B& get_member()
1924             {
1925                 return member;
1926             }
1927         };
1929     When wrapping this class, we would do something like::
1931         module(L)
1932         [
1933             class_<A>("A")
1934                 .def(constructor<>())
1935                 .def("get_member", &A::get_member)
1936         ];
1939     However, since the return value of get_member is a reference to a member of A,
1940     this will create some life-time issues. For example::
1942         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1943         a = A()
1944         b = a:get_member() -- b points to a member of a
1945         a = nil
1946         collectgarbage(0)  -- since there are no references left to a, it is
1947                            -- removed
1948                            -- at this point, b is pointing into a removed object
1950     When using the dependency-policy, it is possible to tell luabind to tie the
1951     lifetime of one object to another, like this::
1953         module(L)
1954         [
1955             class_<A>("A")
1956                 .def(constructor<>())
1957                 .def("get_member", &A::get_member, dependency(result, _1))
1958         ];
1960     This will create a dependency between the return-value of the function, and the
1961     self-object. This means that the self-object will be kept alive as long as the
1962     result is still alive. ::
1964         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1965         a = A()
1966         b = a:get_member() -- b points to a member of a
1967         a = nil
1968         collectgarbage(0)  -- a is dependent on b, so it isn't removed
1969         b = nil
1970         collectgarbage(0)  -- all dependencies to a gone, a is removed
1972     To use this policy you need to include ``luabind/dependency_policy.hpp``.
1975     Return reference to
1976     -------------------
1978     It is very common to return references to arguments or the this-pointer to
1979     allow for chaining in C++.
1981     ::
1983         struct A
1984         {
1985             float val;
1987             A& set(float v)
1988             {
1989                 val = v;
1990                 return *this;
1991             }
1992         };
1994     When luabind generates code for this, it will create a new object for the
1995     return-value, pointing to the self-object. This isn't a problem, but could be a
1996     bit inefficient. When using the return_reference_to-policy we have the ability
1997     to tell luabind that the return-value is already on the Lua stack.
1999     ::
2001         module(L)
2002         [
2003             class_<A>("A")
2004                 .def(constructor<>())
2005                 .def("set", &A::set, return_reference_to(_1))
2006         ];
2008     Instead of creating a new object, luabind will just copy the object that is
2009     already on the stack.
2011     .. warning:: 
2012        This policy ignores all type information and should be used only it 
2013        situations where the parameter type is a perfect match to the 
2014        return-type (such as in the example).
2016     To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
2019     Out value
2020     ---------
2022     This policy makes it possible to wrap functions that take non const references
2023     as its parameters with the intention to write return values to them.
2025     ::
2027         void f(float& val) { val = val + 10.f; }
2029     or
2031     ::
2033         void f(float* val) { *val = *val + 10.f; }
2035     Can be wrapped by doing::
2037         module(L)
2038         [
2039             def("f", &f, out_value(_1))
2040         ];
2042     When invoking this function from Lua it will return the value assigned to its 
2043     parameter.
2045     ::
2047         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
2048         > a = f(10)
2049         > print(a)
2050         20
2052     When this policy is used in conjunction with user define types we often need 
2053     to do ownership transfers.
2055     ::
2057         struct A;
2059         void f1(A*& obj) { obj = new A(); }
2060         void f2(A** obj) { *obj = new A(); }
2062     Here we need to make sure luabind takes control over object returned, for 
2063     this we use the adopt policy::
2065         module(L)
2066         [
2067             class_<A>("A"),
2068             def("f1", &f1, out_value(_1, adopt(_2)))
2069             def("f2", &f2, out_value(_1, adopt(_2)))
2070         ];
2072     Here we are using adopt as an internal policy to out_value. The index 
2073     specified, _2, means adopt will be used to convert the value back to Lua. 
2074     Using _1 means the policy will be used when converting from Lua to C++.
2076     To use this policy you need to include ``luabind/out_value_policy.hpp``.
2078     Pure out value
2079     --------------
2081     This policy works in exactly the same way as out_value, except that it 
2082     replaces the parameters with default-constructed objects.
2084     ::
2086         void get(float& x, float& y)
2087         {
2088             x = 3.f;
2089             y = 4.f;
2090         }
2092         ...
2094         module(L)
2095         [
2096             def("get", &get, 
2097                 pure_out_value(_1) + pure_out_value(_2))
2098         ];
2100     ::
2102         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
2103         > x, y = get()
2104         > print(x, y)
2105         3    5
2107     Like out_value, it is possible to specify an internal policy used then 
2108     converting the values back to Lua.
2110     ::
2112         void get(test_class*& obj)
2113         {
2114             obj = new test_class();
2115         }
2117         ...
2119         module(L)
2120         [
2121             def("get", &get, pure_out_value(_1, adopt(_1)))
2122         ];
2125     Discard result
2126     --------------
2128     This is a very simple policy which makes it possible to throw away 
2129     the value returned by a C++ function, instead of converting it to 
2130     Lua. This example makes sure the this reference never gets converted 
2131     to Lua.
2133     ::
2135         struct simple
2136         {
2137             simple& set_name(const std::string& n)
2138             {
2139                 name = n;
2140                 return *this;
2141             }
2143             std::string name;
2144         };
2146         ...
2148         module(L)
2149         [
2150             class_<simple>("simple")
2151                 .def("set_name", &simple::set_name, discard_result)
2152         ];
2154     To use this policy you need to include ``luabind/discard_result_policy.hpp``.
2157     Return STL iterator
2158     -------------------
2160     This policy converts an STL container to a generator function that can be used
2161     in Lua to iterate over the container. It works on any container that defines
2162     ``begin()`` and ``end()`` member functions (they have to return iterators). It
2163     can be used like this::
2165         struct A
2166         {
2167             std::vector<std::string> names;
2168         };
2171         module(L)
2172         [
2173             class_<A>("A")
2174                 .def_readwrite("names", &A::names, return_stl_iterator)
2175         ];
2177     The Lua code to iterate over the container::
2179         a = A()
2181         for name in a.names do
2182           print(name)
2183         end
2186     To use this policy you need to include ``luabind/iterator_policy.hpp``.
2189     Yield
2190     -----    
2192     This policy will cause the function to always yield the current thread when 
2193     returning. See the Lua manual for restrictions on yield.
2196 Splitting up the registration
2197 =============================
2199 It is possible to split up a module registration into several
2200 translation units without making each registration dependent
2201 on the module it's being registered in.
2203 ``a.cpp``::
2205     luabind::scope register_a()
2206     {
2207         return 
2208             class_<a>("a")
2209                 .def("f", &a::f)
2210                 ;
2211     }
2213 ``b.cpp``::
2215     luabind::scope register_b()
2216     {
2217         return 
2218             class_<b>("b")
2219                 .def("g", &b::g)
2220                 ;
2221     }
2223 ``module_ab.cpp``::
2225     luabind::scope register_a();
2226     luabind::scope register_b();
2228     void register_module(lua_State* L)
2229     {
2230         module("b", L)
2231         [
2232             register_a(),
2233             register_b()
2234         ];
2235     }
2238 Error Handling
2239 ==============
2241 pcall errorfunc
2242 ---------------
2244 As mentioned in the `Lua documentation`_, it is possible to pass an
2245 error handler function to ``lua_pcall()``. Luabind makes use of 
2246 ``lua_pcall()`` internally when calling member functions and free functions.
2247 It is possible to set the error handler function that Luabind will use
2248 globally::
2250     typedef int(*pcall_callback_fun)(lua_State*);
2251     void set_pcall_callback(pcall_callback_fun fn);
2253 This is primarily useful for adding more information to the error message
2254 returned by a failed protected call. For more information on how to use the
2255 pcall_callback function, see ``errfunc`` under the
2256 `pcall section of the lua manual`_.
2258 For more information on how to retrieve debugging information from lua, see
2259 `the debug section of the lua manual`_.
2261 The message returned by the ``pcall_callback`` is accessable as the top lua
2262 value on the stack. For example, if you would like to access it as a luabind
2263 object, you could do like this::
2265     catch(error& e)
2266     {
2267         object error_msg(from_stack(e.state(), -1));
2268         std::cout << error_msg << std::endl;
2269     }
2271 .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
2272 .. _`pcall section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#3.15
2273 .. _`the debug section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#4
2275 file and line numbers
2276 ---------------------
2278 If you want to add file name and line number to the error messages generated
2279 by luabind you can define your own `pcall errorfunc`_. You may want to modify
2280 this callback to better suit your needs, but the basic functionality could be
2281 implemented like this::
2283    int add_file_and_line(lua_State* L)
2284    {
2285       lua_Debug d;
2286       lua_getstack(L, 1, &d);
2287       lua_getinfo(L, "Sln", &d);
2288       std::string err = lua_tostring(L, -1);
2289       lua_pop(L, 1);
2290       std::stringstream msg;
2291       msg << d.short_src << ":" << d.currentline;
2293       if (d.name != 0)
2294       {
2295          msg << "(" << d.namewhat << " " << d.name << ")";
2296       }
2297       msg << " " << err;
2298       lua_pushstring(L, msg.str().c_str());
2299       return 1;
2300    }
2302 For more information about what kind of information you can add to the error
2303 message, see `the debug section of the lua manual`_.
2305 Note that the callback set by ``set_pcall_callback()`` will only be used when
2306 luabind executes lua code. Anytime when you call ``lua_pcall`` yourself, you
2307 have to supply your function if you want error messages translated.
2309 lua panic
2310 ---------
2312 When lua encounters a fatal error caused by a bug from the C/C++ side, it will
2313 call its internal panic function. This can happen, for example,  when you call
2314 ``lua_gettable`` on a value that isn't a table. If you do the same thing from
2315 within lua, it will of course just fail with an error message.
2317 The default panic function will ``exit()`` the application. If you want to
2318 handle this case without terminating your application, you can define your own
2319 panic function using ``lua_atpanic``. The best way to continue from the panic
2320 function is to make sure lua is compiled as C++ and throw an exception from
2321 the panic function. Throwing an exception instead of using ``setjmp`` and
2322 ``longjmp`` will make sure the stack is correctly unwound.
2324 When the panic function is called, the lua state is invalid, and the only
2325 allowed operation on it is to close it.
2327 For more information, see the `lua manual section 3.19`_.
2329 .. _`lua manual section 3.19`: http://www.lua.org/manual/5.0/manual.html#3.19
2331 structured exceptions (MSVC)
2332 ----------------------------
2334 Since lua is generally built as a C library, any callbacks called from lua
2335 cannot under any circumstance throw an exception. Because of that, luabind has
2336 to catch all exceptions and translate them into proper lua errors (by calling
2337 ``lua_error()``). This means we have a ``catch(...) {}`` in there.
2339 In Visual Studio, ``catch (...)`` will not only catch C++ exceptions, it will
2340 also catch structured exceptions, such as segmentation fault. This means that if
2341 your function, that gets called from luabind, makes an invalid memory
2342 adressing, you won't notice it. All that will happen is that lua will return
2343 an error message saying "unknown exception".
2345 To remedy this, you can create your own *exception translator*::
2347    void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
2348    { throw; }
2350    #ifdef _MSC_VER
2351       ::_set_se_translator(straight_to_debugger);
2352    #endif
2354 This will make structured exceptions, like segmentation fault, to actually get
2355 caught by the debugger.
2358 Error messages
2359 --------------
2361 These are the error messages that can be generated by luabind, with a more
2362 in-depth explanation.
2364 - .. parsed-literal::
2366     the attribute '*class-name.attribute-name*' is read only
2368   There is no data member named *attribute-name* in the class *class-name*,
2369   or there's no setter-function registered on that property name. See the 
2370   Properties_ section.
2372 - .. parsed-literal:: 
2374     the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*)
2376   This error is generated if you try to assign an attribute with a value 
2377   of a type that cannot be converted to the attribute's type.
2380 - .. parsed-literal:: 
2382     *class-name()* threw an exception, *class-name:function-name()* threw an exception
2384   The class' constructor or member function threw an unknown exception.
2385   Known exceptions are const char*, std::exception. See the 
2386   `exceptions`_ section.
2388 - .. parsed-literal::
2390     no overload of '*class-name:function-name*' matched the arguments (*parameter-types*)
2391     no match for function call '*function-name*' with the parameters (*parameter-types*)
2392     no constructor of *class-name* matched the arguments (*parameter-types*)
2393     no operator *operator-name* matched the arguments (*parameter-types*)
2395   No function/operator with the given name takes the parameters you gave 
2396   it. You have either misspelled the function name, or given it incorrect
2397   parameters. This error is followed by a list of possible candidate 
2398   functions to help you figure out what parameter has the wrong type. If
2399   the candidate list is empty there's no function at all with that name.
2400   See the signature matching section.
2402 - .. parsed-literal::
2404     call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous
2405     ambiguous match for function call '*function-name*' with the parameters (*parameter-types*)
2406     call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous
2407     call of overloaded operator *operator-name* (*parameter-types*) is ambiguous
2409   This means that the function/operator you are trying to call has at least
2410   one other overload that matches the arguments just as good as the first
2411   overload.
2413 - .. parsed-literal::
2415     cannot derive from C++ class '*class-name*'. It does not have a wrapped type.
2419 Build options
2420 =============
2422 There are a number of configuration options available when building luabind.
2423 It is very important that your project has the exact same configuration 
2424 options as the ones given when the library was build! The exceptions are the
2425 ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based 
2426 options and only matters when you use the library (which means they can 
2427 differ from the settings of the library).
2429 The default settings which will be used if no other settings are given
2430 can be found in ``luabind/config.hpp``.
2432 If you want to change the settings of the library, you can modify the 
2433 config file. It is included and used by all makefiles. You can change paths
2434 to Lua and boost in there as well.
2436 LUABIND_MAX_ARITY
2437     Controls the maximum arity of functions that are registered with luabind. 
2438     You can't register functions that takes more parameters than the number 
2439     this macro is set to. It defaults to 5, so, if your functions have greater 
2440     arity you have to redefine it. A high limit will increase compilation time.
2442 LUABIND_MAX_BASES
2443     Controls the maximum number of classes one class can derive from in 
2444     luabind (the number of classes specified within ``bases<>``). 
2445     ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase 
2446     compilation time.
2448 LUABIND_NO_ERROR_CHECKING
2449     If this macro is defined, all the Lua code is expected only to make legal 
2450     calls. If illegal function calls are made (e.g. giving parameters that 
2451     doesn't match the function signature) they will not be detected by luabind
2452     and the application will probably crash. Error checking could be disabled 
2453     when shipping a release build (given that no end-user has access to write 
2454     custom Lua code). Note that function parameter matching will be done if a 
2455     function is overloaded, since otherwise it's impossible to know which one 
2456     was called. Functions will still be able to throw exceptions when error 
2457     checking is disabled.
2459     If a function throws an exception it will be caught by luabind and 
2460     propagated with ``lua_error()``.
2462 LUABIND_NO_EXCEPTIONS
2463     This define will disable all usage of try, catch and throw in luabind. 
2464     This will in many cases disable run-time errors, when performing invalid 
2465     casts or calling Lua functions that fails or returns values that cannot 
2466     be converted by the given policy. luabind requires that no function called 
2467     directly or indirectly by luabind throws an exception (throwing exceptions 
2468     through Lua has undefined behavior).
2470     Where exceptions are the only way to get an error report from luabind, 
2471     they will be replaced with calls to the callback functions set with
2472     ``set_error_callback()`` and ``set_cast_failed_callback()``.
2474 LUA_API
2475     If you want to link dynamically against Lua, you can set this define to 
2476     the import-keyword on your compiler and platform. On Windows in Visual Studio 
2477     this should be ``__declspec(dllimport)`` if you want to link against Lua 
2478     as a dll.
2480 LUABIND_EXPORT, LUABIND_IMPORT
2481     If you want to link against luabind as a dll (in Visual Studio), you can 
2482     define ``LUABIND_EXPORT`` to ``__declspec(dllexport)`` and 
2483     ``LUABIND_IMPORT`` to ``__declspec(dllimport)`` or
2484     ``__attribute__ ((visibility("default")))`` on GCC 4. 
2485     Note that you have to link against Lua as a dll aswell, to make it work.
2487 LUABIND_NO_RTTI
2488     You can define this if you don't want luabind to use ``dynamic_cast<>``.
2489     It will disable `Object identity`_.
2491 LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO
2492     If you don't want to use the RTTI supplied by C++ you can supply your own 
2493     type-info structure with the ``LUABIND_TYPE_INFO`` define. Your type-info 
2494     structure must be copyable and must be able to compare itself against 
2495     other type-info structures. You supply the compare function through the 
2496     ``LUABIND_TYPE_INFO_EQUAL()`` define. It should compare the two type-info 
2497     structures it is given and return true if they represent the same type and
2498     false otherwise. You also have to supply a function to generate your 
2499     type-info structure. You do this through the ``LUABIND_TYPEID()`` define. 
2500     It should return your type-info structure and it takes a type as its 
2501     parameter. That is, a compile time parameter. 
2502     ``LUABIND_INVALID_TYPE_INFO`` macro should be defined to an invalid type. 
2503     No other type should be able to produce this type info. To use it you 
2504     probably have to make a traits class with specializations for all classes 
2505     that you have type-info for. Like this::
2507         class A;
2508         class B;
2509         class C;
2511         template<class T> struct typeinfo_trait;
2513         template<> struct typeinfo_trait<A> { enum { type_id = 0 }; };
2514         template<> struct typeinfo_trait<B> { enum { type_id = 1 }; };
2515         template<> struct typeinfo_trait<C> { enum { type_id = 2 }; };
2517     If you have set up your own RTTI system like this (by using integers to
2518     identify types) you can have luabind use it with the following defines::
2520         #define LUABIND_TYPE_INFO const std::type_info*
2521         #define LUABIND_TYPEID(t) &typeid(t)
2522         #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
2523         #define LUABIND_INVALID_TYPE_INFO &typeid(detail::null_type)
2525     Currently the type given through ``LUABIND_TYPE_INFO`` must be less-than 
2526     comparable!
2528 NDEBUG
2529     This define will disable all asserts and should be defined in a release 
2530     build.
2533 Implementation notes
2534 ====================
2536 The classes and objects are implemented as user data in Lua. To make sure that
2537 the user data really is the internal structure it is supposed to be, we tag
2538 their metatables. A user data who's metatable contains a boolean member named
2539 ``__luabind_classrep`` is expected to be a class exported by luabind. A user
2540 data who's metatable contains a boolean member named ``__luabind_class`` is
2541 expected to be an instantiation of a luabind class.
2543 This means that if you make your own user data and tags its metatable with the
2544 exact same names, you can very easily fool luabind and crash the application.
2546 In the Lua registry, luabind keeps an entry called ``__luabind_classes``. It
2547 should not be removed or overwritten.
2549 In the global table, a variable called ``super`` is used every time a
2550 constructor in a lua-class is called. This is to make it easy for that
2551 constructor to call its base class' constructor. So, if you have a global
2552 variable named super it may be overwritten. This is probably not the best
2553 solution, and this restriction may be removed in the future.
2555 .. note:: Deprecated
2557   ``super()`` has been deprecated since version 0.8 in favor of directly
2558   invoking the base class' ``__init()`` function::
2560     function Derived:__init()
2561         Base.__init(self)
2562     end
2564 Luabind uses two upvalues for functions that it registers. The first is a
2565 userdata containing a list of overloads for the function, the other is a light
2566 userdata with the value 0x1337, this last value is used to identify functions
2567 registered by luabind. It should be virtually impossible to have such a pointer
2568 as secondary upvalue by pure chance. This means, if you are trying to replace
2569 an existing function with a luabind function, luabind will see that the
2570 secondary upvalue isn't the magic id number and replace it. If it can identify
2571 the function to be a luabind function, it won't replace it, but rather add
2572 another overload to it.
2574 Inside the luabind namespace, there's another namespace called detail. This
2575 namespace contains non-public classes and are not supposed to be used directly.
2581 What's up with __cdecl and __stdcall?
2582     If you're having problem with functions
2583     that cannot be converted from ``void (__stdcall *)(int,int)`` to 
2584     ``void (__cdecl*)(int,int)``. You can change the project settings to make the
2585     compiler generate functions with __cdecl calling conventions. This is
2586     a problem in developer studio.
2588 What's wrong with functions taking variable number of arguments?
2589     You cannot register a function with ellipses in its signature. Since
2590     ellipses don't preserve type safety, those should be avoided anyway.
2592 Internal structure overflow in VC
2593     If you, in visual studio, get fatal error C1204: compiler limit :
2594     internal structure overflow. You should try to split that compilation
2595     unit up in smaller ones. See `Splitting up the registration`_ and
2596     `Splitting class registrations`_.
2598 What's wrong with precompiled headers in VC?
2599     Visual Studio doesn't like anonymous namespace's in its precompiled 
2600     headers. If you encounter this problem you can disable precompiled 
2601     headers for the compilation unit (cpp-file) that uses luabind.
2603 error C1076: compiler limit - internal heap limit reached in VC
2604     In visual studio you will probably hit this error. To fix it you have to
2605     increase the internal heap with a command-line option. We managed to
2606     compile the test suit with /Zm300, but you may need a larger heap then 
2607     that.
2609 error C1055: compiler limit \: out of keys in VC
2610     It seems that this error occurs when too many assert() are used in a
2611     program, or more specifically, the __LINE__ macro. It seems to be fixed by
2612     changing /ZI (Program database for edit and continue) to /Zi 
2613     (Program database).
2615 How come my executable is huge?
2616     If you're compiling in debug mode, you will probably have a lot of
2617     debug-info and symbols (luabind consists of a lot of functions). Also, 
2618     if built in debug mode, no optimizations were applied, luabind relies on 
2619     that the compiler is able to inline functions. If you built in release 
2620     mode, try running strip on your executable to remove export-symbols, 
2621     this will trim down the size.
2623     Our tests suggests that cygwin's gcc produces much bigger executables 
2624     compared to gcc on other platforms and other compilers.
2626 .. HUH?! // check the magic number that identifies luabind's functions 
2628 Can I register class templates with luabind?
2629     Yes you can, but you can only register explicit instantiations of the 
2630     class. Because there's no Lua counterpart to C++ templates. For example, 
2631     you can register an explicit instantiation of std::vector<> like this::
2633         module(L)
2634         [
2635             class_<std::vector<int> >("vector")
2636                 .def(constructor<int>)
2637                 .def("push_back", &std::vector<int>::push_back)
2638         ];
2640 .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
2642 Do I have to register destructors for my classes?
2643     No, the destructor of a class is always called by luabind when an 
2644     object is collected. Note that Lua has to own the object to collect it.
2645     If you pass it to C++ and gives up ownership (with adopt policy) it will 
2646     no longer be owned by Lua, and not collected.
2648     If you have a class hierarchy, you should make the destructor virtual if 
2649     you want to be sure that the correct destructor is called (this apply to C++ 
2650     in general).
2652 .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ. But it saves us support questions.
2654 Fatal Error C1063 compiler limit \: compiler stack overflow in VC
2655     VC6.5 chokes on warnings, if you are getting alot of warnings from your 
2656     code try suppressing them with a pragma directive, this should solve the 
2657     problem.
2659 Crashes when linking against luabind as a dll in Windows
2660     When you build luabind, Lua and you project, make sure you link against 
2661     the runtime dynamically (as a dll).
2663 I cannot register a function with a non-const parameter
2664     This is because there is no way to get a reference to a Lua value. Have 
2665     a look at out_value_ and pure_out_value_ policies.
2668 Known issues
2669 ============
2671 - You cannot use strings with extra nulls in them as member names that refers
2672   to C++ members.
2674 - If one class registers two functions with the same name and the same
2675   signature, there's currently no error. The last registered function will
2676   be the one that's used.
2678 - In VC7, classes can not be called test.
2680 - If you register a function and later rename it, error messages will use the
2681   original function name.
2683 - luabind does not support class hierarchies with virtual inheritance. Casts are
2684   done with static pointer offsets.
2687 Acknowledgments
2688 ===============
2690 Written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
2691 All rights reserved.
2693 Evan Wies has contributed with thorough testing, countless bug reports
2694 and feature ideas.
2696 This library was highly inspired by Dave Abrahams' Boost.Python_ library.
2698 .. _Boost.Python: http://www.boost.org/libraries/python