*** empty log message ***
[luabind.git] / doc / docs.rst
blob7552773dcc2f2533cd448b84d1fa736bf480660b
1 +++++++++
2  luabind
3 +++++++++
5 .. _MIT license: http://www.opensource.org/licenses/mit-license.php
6 .. _Boost: http://www.boost.org
8 Note: This library is currently in public beta phase. This documentation 
9 should be considered beta as well. Please report any grammatical 
10 corrections/spelling corrections.
13 .. contents::
14 .. section-numbering::
16 Introduction
17 ============
19 Luabind is a library that helps you create bindings between C++ and lua. It has
20 the ability to expose functions and classes, written in C++, to lua. It will
21 also supply the functionality to define classes in lua and let them derive from
22 other lua classes or C++ classes. Lua classes can override virtual functions
23 from their C++ base classes. It is written towards lua 5.0, and does not work
24 with lua 4.
26 It is implemented utilizing template meta programming. That means that you
27 don't need an extra preprocess pass to compile your project (it is done by the
28 compiler). It also means you don't (usually) have to know the exact signature of
29 each function you register, since the library will generate code depending on
30 the compile-time type of the function (which includes the signature). The main
31 drawback of this approach is that the compilation time will increase for the
32 file that does the registration, it is therefore recommended that you register
33 everything in the same cpp-file.
35 luabind is released under the terms of the `MIT license`_.
37 We are very interested in hearing about projects that use luabind, please let
38 us know about your project.
41 Features
42 ========
44 Luabind supports:
46  - Overloaded free functions 
47  - C++ classes in lua 
48  - Overloaded member functions 
49  - Operators 
50  - Properties 
51  - Enums 
52  - Lua functions in C++ 
53  - Lua classes in C++ 
54  - Lua classes (single inheritance) 
55  - Derives from lua or C++ classes 
56  - O verride virtual functions from C++ classes 
57  - Implicit casts between registered types 
58  - Best match signature matching 
59  - Return value policies and parameter policies 
62 Portability
63 ===========
65 Luabind has been tested to work on the following compilers:
67  - Visual Studio 7.1 
68  - Visual Studio 7.0 
69  - Visual Studio 6.0 (sp 5) 
70  - Intel C++ 6.0 (Windows) 
71  - GCC 2.95.3 (cygwin) 
72  - GCC 3.0.4 (Debian/Linux) 
73  - GCC 3.1 (SunOS 5.8) 
74  - GCC 3.2 (cygwin) 
75  - GCC 3.3.1 (cygwin) 
77 It has been confirmed not to work with:
79  - GCC 2.95.2 (SunOS 5.8) 
81 Metrowerks 8.3 (Windows) compiles but fails the const-test. This 
82 means that const member functions are treated as non-const member 
83 functions.
85 If you have tried luabind with a compiler not listed here, let us know 
86 your result with it.
89 Building luabind
90 ================
92 To keep down the compilation-time luabind is built as a library. This means you
93 have to either build it and lika against it, or include its source files in
94 your project. You also have to make sure the luabind directory is somewhere in
95 your compiler's include path. It requires `Boost`_ 1.31.0 to be installed (only
96 boost headers). It also requires that lua is installed.
98 The official way of building luabind is with `Boost.Build V2`_. To properly build
99 luabind with Boost.Build you need to set two environment variables:
101 BOOST_ROOT
102     Point this to your Boost installation.
104 LUA_PATH
105     Point this to your lua directory. The build system will assume that the
106     include and library files are located in ``$(LUA_PATH)/include/`` and
107     ``$(LUA_PATH)/lib/.``
109 For backward compatibility, there is also a makefile in the root-directory that
110 will build the library and the test program. If you are using a UNIX-system (or
111 cygwin) they will make it easy to build luabind as a static library. If you are
112 using Visual Studio it may be easier to include the files in the src directory
113 in your project.
115 When building luabind you have several options that may streamline the library
116 to better suit your needs. It is extremely important that your application has
117 the same settings as the library was built with. The available options are
118 found in the `Configuration`_ section.
120 If you want to change the settings to differ from the default, it's recommended
121 that you define the settings on the commandline of all your files (in the
122 project settings in visual studio).
124 .. _`Boost.Build V2`: http://www.boost.org/tools/build/v2/index_v2.html
127 Basic usage
128 ===========
130 To use luabind, you must include ``lua.h`` and luabind's main header file::
132     extern "C"
133     {
134         #include "lua.h"
135     }
137     #include <luabind/luabind.hpp>
139 This includes support for both registering classes and functions. If you just
140 want to have support for functions or classes you can include
141 ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
143     #include <luabind/function.hpp>
144     #include <luabind/class.hpp>
146 The first thing you need to do is to call ``luabind::open(lua_State*)`` which
147 will register the functions to create classes from lua, and initialize some
148 state-global structures used by luabind. If you don't call this function you
149 will hit asserts later in the library. There is no corresponding close function
150 because once a class has been registered in lua, there really isn't any good
151 way to remove it. Partly because any remaining instances of that class relies
152 on the class being there. Everything will be cleaned up when the state is
153 closed though.
155 .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
157 Note that no luabind header will include ``lua.h``, this is up to you. You have
158 to include it before any luabind header is included.
161 Hello world
162 -----------
166     #include <iostream>
167     #include <luabind/luabind.hpp>
169     void greet()
170     {
171         std::cout << "hello world!\n";
172     }
174     extern "C" int init(lua_State* L)
175     {
176         using namespace luabind;
178         open(L);
180         module(L)
181         [
182             def("greet", &greet)
183         ];
185         return 0;
186     }
190     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
191     > loadlib('hello_world.dll', 'init')()
192     > greet()
193     Hello world!
194     >
196 Scopes
197 ======
199 Everything that gets registered in lua is registered in a namespace (lua
200 tables) or in the global scope (called module). All registrations must be
201 surrounded by its scope. To define a module, the ``luabind::module`` class is
202 used. It is used like this::
204     module(L)
205     [
206         // declarations
207     ];
209 This will register all declared functions or classes in the global namespace in
210 lua. If you want to have a namespace for your module (like the standard
211 libraries) you can give a name to the constructor, like this::
213     module(L, "my_library")
214     [
215         // declarations
216     ];
218 Here all declarations will be put in the my_library table.
220 If you want nested namespaces you can use the ``luabind::namespace_`` class. It
221 works exactly as ``luabind::module`` except that it doesn't take a lua_State*
222 in it's constructor. An example of its usage could look like this::
224     module(L, "my_library")
225     [
226         // declarations
228         namespace_("detail")
229         [
230             // library-private declarations
231         ]
232     ];
234 As you might have figured out, the following declarations are equivalent::
236     module(L)
237     [
238         namespace_("my_library")
239         [
240             // declarations
241         ]
243     ];
246     
247     module(L, "my_library")
248     [
249         // declarations
250     ];
252 Each declaration must be separated by a comma, like this::
254     module(L)
255     [
256         def("f", &f),
257         def("g", &g),
258         class_<A>("A")
259             .def(constructor<int, int>),
260         def("h", &h)
261     ];
264 More about the actual declarations in the `Binding functions to lua`_ and
265 `Binding classes to lua`_ sections.
267 A word of caution, if you are in really bad need for performance, putting your
268 functions in tables will increase the lookup time.
271 Binding functions to lua
272 ========================
274 To bind functions to lua you use the function ``luabind::def()``. It has the
275 following synopsis::
277     template<class F, class policies>
278     void def(const char* name, F f, const Policies&);
280 - name is the name the function will have within lua. 
281 - F is the function pointer you want to register. 
282 - The Policies parameter is used to describe how parameters and return values 
283   are treated by the function, this is an optional parameter. More on this in 
284   the `policies`_ section.
286 An example usage could be if you want to register the function ``float
287 std::sin(float)``::
289     module(L)
290     [
291         def("sin", &std::sin)
292     ];
294 Overloaded functions
295 --------------------
297 If you have more than one function with the same name, and want to register
298 them in lua, you have to explicitly give the signature. This is to let C++ know
299 which function you refer to. For example, if you have two functions, ``int
300 f(const char*)`` and ``void f(int)``. ::
302     module(L)
303     [
304         def("f", (int(*)(const char*)) &f),
305         def("f", (void(*)(int)) &f)
306     ];
308 Signature matching
309 ------------------
311 luabind will generate code that checks the lua stack to see if the values there
312 can match your functions' signatures. It will handle implicit typecasts between
313 derived classes, and it will prefer matches with the least number of implicit
314 casts. In a function call, if the function is overloaded and there's no
315 overload that match the parameters better than the other, you have an
316 ambiguity. This will spawn a run-time error, stating that the function call is
317 ambiguous. A simple example of this is to register one function that takes an
318 int and one that takes a float. Since lua don't distinguish between floats and
319 integers, both will always match.
321 Since all overloads are tested, it will always find the best match (not the
322 first match). This also means that it can handle situations where the only
323 difference in the signature is that one member function is const and the other
324 isn't. 
326 .. sidebar:: Ownership transfer
328    To correctly handle ownership transfer, create_a() would need an adopt
329    return value policy. More on this in the `Policies`_ section.
331 For example, if the following function and class is registered:
334    
335     struct A
336     {
337         void f();
338         void f() const;
339     };
341     const A* create_a();
343     struct B: A {};
344     struct C: B {};
346     void g(A*);
347     void g(B*);
349 And the following lua code is executed::
351     a1 = create_a()
352     a1:f() -- the const version is called
354     a2 = A()
355     a2:f() -- the non-const version is called
357     a = A()
358     b = B()
359     c = C()
361     g(a) -- calls g(A*)
362     g(b) -- calls g(B*)
363     g(c) -- calls g(B*)
366 Calling lua functions
367 ---------------------
369 To call a lua function, you can either use ``call_function()``,
370 ``call_member()``, an ``object`` or ``functor``.
374     template<class Ret>
375     Ret call_function(lua_State* L, const char* name, ...)
377 This calls the global function called name. This function can only call global
378 lua functions. The ... represents a variable number of parameters that are sent
379 to the lua function. This function call may throw ``luabind::error`` if the
380 function call fails.
382 The return value isn't actually Ret (the template parameter), but a proxy
383 object that will do the function call. This enables you to give policies to the
384 call. You do this with the operator[]. You give the policies within the
385 brackets, like this::
387     int ret = call_function<int>(
388         L 
389       , "a_lua_function"
390       , new complex_class()
391     )[ adopt(_1) ];
395     template<class Ret>
396     Ret call_member(object&, const char* name, ...)
398 This treats the given object as an instance of a class. The given name is the
399 name of a member function to call. The ... represents a variable number of
400 parameters given to the function. This function may throw ``luabind::error`` if
401 the function call fails.
403 You can give policies to a member function call the same way as you do with
404 ``call_function``.
407 Using lua threads
408 -----------------
410 To start a lua thread, you have to call ``lua_resume()``, this means that you
411 cannot use the previous function ``call_function()`` to start a thread. You have
412 to use
416     template<class Ret>
417     Ret resume_function(lua_State* L, const char* name, ...)
423     template<class Ret>
424     Ret resume(lua_State* L, ...)
426 The first time you start the thread, you have to give it a function to execute. i.e. you
427 have to use ``resume_function``, when the lua function yeilds, it will return the first
428 value passed in to ``lua_yield()``. When you want to continue the execution, you just call
429 ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
430 it one. The parameters to ``resume()`` will be returned by ``yield()`` on the lua side.
432 For yielding C++-functions (without the support of passing data back and forth between the
433 lua side and the c++ side), you can use the Yield_ policy.
436 Binding classes to lua
437 ======================
439 To register classes you use a class called ``class_``. Its name is supposed to
440 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
441 member function ``def()`` that is used to register member functions, operators,
442 constructors, enums and properties on the class. It will return its
443 this-pointer, to let you register more members directly.
445 Let's start with a simple example. Consider the following C++ class::
447     class testclass
448     {
449     public:
450         testclass(const std::string& s): m_string(s) {}
451         void print_string() { std::cout << m_string << "\n"; }
453     private:
454         std::string m_string;
455     };
457 To register it with a lua environment, write as follows (assuming you are using
458 namespace luabind)::
460     module(L)
461     [
462         class_<testclass>("testclass")
463             .def(constructor<const std::string&>())
464             .def("print_string", &testclass::print_string)
465     ];
467 This will register the class with the name testclass and constructor that takes
468 a string as argument and one member function with the name ``print_string``.
472     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
473     > a = testclass('a string')
474     > a:print_string()
475     a string
477 It is also possible to register free functions as member functions. The
478 requirement on the function is that it takes a pointer, const pointer,
479 reference or const reference to the class type as the first parameter. The rest
480 of the parameters are the ones that are visible in lua, while the object
481 pointer is given as the first parameter. If we have the following C++ code::
483     struct A
484     {
485         int a;
486     };
488     int plus(A* o, int v) { return o->a + v; }
490 You can register ``plus()`` as if it was a member function of A like this::
492     class_<A>("A")
493         .def("plus", &plus)
495 ``plus()`` can now be called as a member function on A with one parameter, int.
496 If the object pointer parameter is const, the function will act as if it was a
497 const member function (it can be called on const objects).
500 Properties
501 ----------
503 To register a global data member with a class is easily done. Consider the
504 following class::
506     struct A
507     {
508         int a;
509     };
511 This class is registered like this::
513     module(L)
514     [
515         class_<A>("A")
516             .def_readwrite("a", &A::a)
517     ];
519 This gives read and write access to the member variable ``A::a``. It is also
520 possible to register attributes with read-only access::
522     module(L)
523     [
524         class_<A>("A")
525         .def_readonly("a", &A::a)
526     ];
528 You can also register getter and setter functions and make them look as if they
529 were a public data member. Consider the following class::
531     class A
532     {
533     public:
534         void set_a(int x) { a = x; }
535         int get_a() const { return a; }
537     private:
538         int a;
539     };
541 It can be registered as if it had a public data member a like this::
543     class_<A>("A")
544         .property("a", &A::get_a, &A::set_a)
546 This way the ``get_a()`` and ``set_a()`` functions will be called instead of
547 just writing  to the data member. If you want to make it read only you can just
548 omit the last parameter.
551 Enums
552 -----
554 If your class contains enumerated constants (enums), you can register them as
555 well to make them available in lua. Note that they will not be type safe, all
556 enums are integers in lua, and all functions that takes an enum, will accept
557 any integer. You register them like this::
559     module(L)
560     [
561         class_<A>("A")
562             .enum_("constants")
563             [
564                 value("my_enum", 4),
565                 value("my_2nd_enum", 7),
566                 value("another_enum", 6)
567             ]
568     ];
570 In lua they are accessed like any data member, except that they are read-only
571 and reached on the class itself rather than on an instance of the class.
575     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
576     > print(A.my_enum)
577     4
578     > print(A.another_enum)
579     6
582 Operators
583 ---------
585 The mechanism for registering operators on your class is pretty simple. You use
586 a global name ``luabind::self`` to refer to the class itself and then you just
587 write the operator expression inside the ``def()`` call. This class::
589     struct vec
590     {
591         vec operator+(int s);
592     };
594 Is registered like this::
596     module(L)
597     [
598         class_<vec>("vec")
599             .def(self + int())
600     ];
602 This will work regardless if your plus operator is defined inside your class or
603 as a free function.
605 If you operator is const (or, when defined as a free function, takes a const
606 reference to the class itself) you have to use ``const_self`` instead of
607 ``self``. Like this::
609     module(L)
610     [
611         class_<vec>("vec")
612             .def(const_self + int())
613     ];
615 The operators supported are those available in lua:
617  - \+
618  - \-
619  - \*
620  - \/
622  .. more
624 This means, no in-place operators. The equality operator (==) has a little
625 hatch, it will not be called if the references are equal. This means that the
626 == operator has to do pretty much what's it's expected to do.
628 In the above example the other operand type is instantiated by writing
629 ``int()``. If the operand type is a complex type that cannot easily be
630 instantiated you can wrap the type in a class called ``other<>``. For example:
632 To register this class, we don't want to instantiate a string just to register
633 the operator.
637     struct vec
638     {
639         vec operator+(std::string);
640     };
642 Instead we use the other ``wrapper`` like this::
644     module(L)
645     [
646         class_<vec>("vec")
647             .def(self + other<std::string>())
648     ];
650 To register an application operator::
652     module(L)
653     [
654         class_<vec>("vec")
655             .def( self(int()) )
656     ];
658 There's one special operator. In lua it's called ``__tostring``, it's not
659 really an operator. It is used for converting objects to strings in a standard
660 way in lua. If you register this functionality, you will be able to use the lua
661 standard function ``tostring()`` for converting you object to a string.
663 To implement this operator in C++ you should supply an ``operator<<`` for
664 ostream. Like this example::
666     class number {};
667     std::ostream& operator<<(std::ostream&, number&);
669     ...
670     
671     module(L)
672     [
673         class_<number>("number")
674             .def(tostring(self))
675     ];
678 Nested scopes and static functions
679 ----------------------------------
681 It is possible to add nested scopes to a class. This is useful when you need 
682 to wrap a nested class, or a static function. ::
684     class_<foo>("foo")
685         .def(constructor<>()
686         ...
687         .scope
688         [
689             class_<inner>("nested"),
690             def("f", &f)
691         ];
693 It's also possible to add namespaces to classes using the same syntax.
696 Derived classes
697 ---------------
698   
699 If you want to register classes that derives from other classes, you can
700 specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
701 following hierarchy::
702    
703     struct A {};
704     struct B : A {};
706 Would be registered like this::
708     module(L)
709     [
710         class_<A>("A"),
711         class_<B, A>("B")
712     ];
714 If you have multiple inheritance you can specify more than one base. If B would
715 also derive from a class C, it would be registered like this::
717     module(L)
718     [
719         class_<B, bases<A, C> >("B")
720     ];
722 Note that you can omit ``bases<>`` when using single inheritance.
724 .. note::
725    If you don't specify that classes derive from each other, luabind will not
726    be able to implicitly cast pointers between the types.
729 Smart pointers
730 --------------
732 When you register a class you can tell luabind that all instances of that class
733 should be held by some kind of smart pointer (boost::shared_ptr for instance).
734 You do this by giving the holder type as an extra template parameter to
735 the``class_``your constructing, like this::
737     module(L)
738     [
739         class_<A, boost::shared_ptr<A> >("A")
740     ];
742 You also have to supply two functions for your smart pointer. One that returns
743 the type of const version of the smart pointer type (boost::shared_ptr<const A>
744 in this case). And one function that extracts the raw pointer from the smart
745 pointer. The first function is needed because luabind has to allow the
746 non-const -> conversion when passing values from lua to C++. The second
747 function is needed when lua calls member functions on held types, the this
748 pointer must be a raw pointer, it is also needed to allow the smart_pointer ->
749 raw_pointer conversion from lua to C++. They look like this::
751     namespace luabind {
753         template<class T>
754         T* get_pointer(boost::shared_ptr<T>& p) 
755         { 
756             return p.get(); 
757         }
759         template<class A>
760         boost::shared_ptr<const A>* 
761         get_const_holder(boost::shared_ptr<A>*)
762         {
763             return 0;
764         }
765     }
767 The conversion that works are (given that B is a base class of A):
769 +----------------------------------------------+
770 |          From lua to C++                     |
771 +======================+=======================+
772 | holder_type<A>       | A*                    |
773 +----------------------+-----------------------+
774 | holder_type<A>       | A*                    |
775 +----------------------+-----------------------+
776 | holder_type<A>       | const A*              |
777 +----------------------+-----------------------+
778 | holder_type<A>       | const B*              |
779 +----------------------+-----------------------+
780 | holder_type<A>       | holder_type<A>        |
781 +----------------------+-----------------------+
782 | holder_type<A>       | holder_type<const A>  |
783 +----------------------+-----------------------+
784 | holder_type<const A> | const A*              |
785 +----------------------+-----------------------+
786 | holder_type<const A> | const B*              |
787 +----------------------+-----------------------+
788 | holder_type<const A> | holder_type<const A>  |
789 +----------------------+-----------------------+
791 +-----------------------------------------------------+
792 |          From C++ to lua                            |
793 +=============================+=======================+
794 | holder_type<A>              | holder_type<A>        |
795 +-----------------------------+-----------------------+
796 | holder_type<const A>        | holder_type<const A>  |
797 +-----------------------------+-----------------------+
798 | const holder_type<A>&       | holder_type<A>        |
799 +-----------------------------+-----------------------+
800 | const holder_type<const A>& | holder_type<const A>  |
801 +-----------------------------+-----------------------+
803 When using a holder type, it can be useful to know if the pointer is valid. For
804 example when using std::auto_ptr, the holder will be invalidated when passed as
805 a parameter to a function. For this purpose there is a member of all object
806 instances in luabind: ``__ok``. ::
808     struct test {};
809     void f(std::auto_ptr<test>);
811     module(L)
812     [
813         class_<test>("test")
814             .def(constructor<>()),
816         def("f", &f)
817     ];
820     
821     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
822     > a = test()
823     > f(a)
824     > print a.__ok
825     false
828 Object
829 ======
831 Since functions have to be able to take lua values (of variable type) we need a
832 wrapper around them. This wrapper is called ``luabind::object``. If the
833 function you register takes an object, it will match any lua value. To use it,
834 you need to include ``luabind/object.hpp``. The object class has the following
835 synopsis::
837     class object
838     {
839     public:
840         class iterator;
841         class raw_iterator;
842         class array_iterator;
844         template<class T>
845         object(lua_State*, const T& value);
846         object(const object&);
847         object(lua_State*);
848         object();
850         ~object();
851         
852         iterator begin() const;
853         iterator end() const;
854         raw_iterator raw_begin() const;
855         raw_iterator raw_end() const;
856         array_iterator abegin() const;
857         array_iterator aend() const;
859         void set();
860         lua_State* lua_state() const;
861         void pushvalue() const;
862         bool is_valid() const;
863         operator safe_bool_type() const;
865         template<class Key>
866         <implementation-defined> operator[](const Key&);
868         template<class Key>
869         object at(const Key&) const;
871         template<class Key>
872         object raw_at(const Key&) const;
874         template<class T>
875         object& operator=(const T&);
876         object& operator=(const object&);
878         template<class T>
879         bool operator==(const T&) const;
880         bool operator==(const object&) const;
881         bool operator<(const object&) const;
882         bool operator<=(const object&) const;
883         bool operator>(const object&) const;
884         bool operator>=(const object&) const;
885         bool operator!=(const object&) const;
887         void swap(object&);
888         int type() const;
890         <implementation-defined> operator()();
891         
892         template<class A0>
893         <implementation-defined> operator()(const A0& a0);
895         template<class A0, class A1>
896         <implementation-defined> operator()(const A0& a0, const A1& a1);
898         /* ... */
899         
900     };
902 When you have a lua object, you can assign it a new value with the assignment
903 operator (=). When you do this, the ``default_policy`` will be used to make the
904 conversion from C++ value to lua. If your ``luabind::object`` is a table you
905 can access its members through the operator[] or the iterators. The value
906 returned from the operator[] is a proxy object that can be used both for
907 reading and writing values into the table (using operator=). Note that it is
908 impossible to know if a lua value is indexable or not (lua_gettable doesn't
909 fail, it succeeds or crashes). This means that if you're trying to index
910 something that cannot be indexed, you're on your own. Lua will call its
911 ``panic()`` function (you can define your own panic function using
912 lua_setpanicf). The ``at()`` and ``raw_at()`` functions returns the value at
913 the given table position (like operator[] but only for reading).
915 The ordinary ``object::iterator`` uses lua_gettable to extract the values from
916 the table, the standard way that will invoke metamethods if any. The
917 ``object::raw_iterator`` uses lua_rawget and ``object::array_iterator`` uses
918 lua_rawgeti. The latter will only iterate over numberical keys starting at 1
919 and continue until the first nil value.
921 The ``lua_state()`` function returns the lua state where this object is stored.
922 If you want to manipulate the object with lua functions directly you can push
923 it onto the lua stack by calling ``pushvalue()``. And set the object's value by
924 calling ``set()``, which will pop the top value from the lua stack and assign
925 it to the object.
927 The operator== will call lua_equal() on the operands and return its result.
929 The ``type()`` member function will return the lua type of the object. It will
930 return the same values as lua_type().
932 The ``is_valid()`` function tells you whether the object has been initialized
933 or not. When created with its default constructor, objects are invalid. To make
934 an object valid, you can assign it a value. If you want to invalidate an object
935 you can simply assign it an invalid object.
937 .. So what? implementation detail, leave out of docs
938   isn't really an implicit cast to bool, but an implicit cast
939   to a member pointer, since member pointers don't have any arithmetic operators
940   on them (which can cause hard to find errors). The functionality of the cast
941   operator
943 The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
944 that these snippets are equivalent::
946     object o;
947     // ...
948     if (o)
949     {
950         // ...
951     }
953     ...
955     object o;
956     // ...
957     if (o.is_valid())
958     {
959         // ...
960     }
962 The application operator will call the value as if it was a function. You can
963 give it any number of parameters (currently the ``default_policy`` will be used
964 for the conversion). The returned object refers to the return value (currently
965 only one return value is supported). This operator may throw ``luabind::error``
966 if the function call fails. If you want to specify policies to your function
967 call, you can use index-operator (operator[]) on the function call, and give
968 the policies within the [ and ]. Like this::
970     my_function_object(
971         2
972       , 8
973       , new my_complex_structure(6)
974     ) [ adopt(_3) ];
976 This tells luabind to make lua adopt the ownership and responsibility for the
977 pointer passed in to the lua-function.
979 It's important that all instances of object have been destructed by the time
980 the lua state is closed. The object will keep a pointer to the lua state and
981 release its lua object in its destructor.
983 Here's an example of how a function can use a table::
985     void my_function(const object& table)
986     {
987         if (table.type() == LUA_TTABLE)
988         {
989             table["time"] = std::clock();
990             table["name"] = std::rand() < 500 ? "unusual" : "usual";
992             std::cout << object_cast<std::string>(table[5]) << "\n";
993         }
994     }
996 If you take a ``luabind::object`` as a parameter to a function, any lua value
997 will match that parameter. That's why we have to make sure it's a table before
998 we index into it.
1001 Iterators
1002 ---------
1004 The iterators, that are returned by ``begin() and ``end()`` (and their
1005 variants) are (almost) models of the ForwardIterator concept. The exception
1006 is that post increment doesn't exist on them.
1008 They look like this::
1010     class object::iterator
1011     {
1012         iterator();
1013         iterator(const iterator&);
1015         iterator& operator++();
1016         bool operator!=(const iterator&) const;
1017         iterator& operator=(const iterator&);
1019         object key() const;
1021         implementation-defined operator*();
1022     };
1024 The implementation defined return value from the dereference operator is a
1025 proxy object that can be used as if it was an object, it can also be used to
1026 assign the specific table entry with a new value. If you want to assign a value
1027 to an entry pointed to by an iterator, just use the assignment operator on the
1028 dereferenced iterator::
1030     *iter = 5;
1032 The ``key()`` member returns the key used by the iterator when indexing the
1033 associated lua table.
1036 Related functions
1037 -----------------
1039 There are a couple of functions related to objects and tables. ::
1041     T object_cast<T>(const object&);
1042     T object_cast<T>(const object&, const Policies&);
1044     boost::optional<T> 
1045     object_cast_nothrow<T>(const object&);
1047     boost::optional<T>  
1048     object_cast_nothrow<T>(const object&, const Policies&);
1051 Functor
1052 -------
1054 The ``functor`` class is similar to object, with the exception that it can only
1055 be used to store functions. If you take it as a parameter, it will only match
1056 functions.
1058 To use it you need to include its header::
1060     #include <luabind/functor.hpp>
1062 It takes one template parameter, the return value of the lua function it
1063 represents. Currently the functor can have at most one return value (unlike lua
1064 functions). It has the following synopsis::
1066     template<class Ret>
1067     class functor
1068     {
1069     public:
1071         functor(lua_State*, const char* name);
1072         functor(const functor&);
1074         ~functor();
1075         
1076         bool is_valid() const;
1077         operator safe_bool_type() const;
1078         void reset();
1080         lua_State* lua_state() const;
1081         void pushvalue() const;
1082         
1083         bool operator==(const functor<Ret>&);
1084         bool operator!=(const functor<Ret>&);
1085         
1086         <implementation-defined> operator()() const;
1087         
1088         template<class A0>
1089         <implementation-defined> operator()(const A0&) const;
1091         template<class A0, class A1>
1092         <implementation-defined> operator()(const A0&, const A1&) const;
1094         /* ... */
1095     };
1097 The application operator takes any parameters. The parameters are converted
1098 into lua and the function is called. The return value will act as if it was the
1099 type Ret, with the exception that you can use the return value to give policies
1100 to the call. You do this the same way as you do with objects, using the
1101 operator[], and giving the policies inside the brackets.
1103 The ``is_valid()`` function works just like the one on object, it tells you if
1104 the functor has been assigned with a valid lua function. The ``operator
1105 safe_bool_type()`` is an alias for this member function and also works just as
1106 the one found in object.
1108 For example, if you have the following lua function::
1110     function f(a, b)
1111         return a + b
1112     end
1114 You can expose it to C++ like this::
1116     functor<int> f(L, "f");
1118     std::cout << f(3, 5) << "\n";
1120 This will print out the sum of 3 and 5. Note that you can pass any parameters
1121 to the application operator of ``luabind::functor``, this is because lua
1122 doesn't have signatures for its functions. All lua functions take any number of
1123 parameters of any type.
1125 If we have a C++ function that takes a ``luabind::functor`` and registers it,
1126 it will accept lua functions passed to it. This enables us to expose APIs that
1127 requires you to register callbacks. For example, if your C++ API looks like
1128 this::
1130     void set_callback(void(*)(int, int));
1132 And you want to expose it to lua, you have to wrap the call to the lua 
1133 function inside a real C++ function, like this::
1135     functor<void> lua_callback;
1137     void callback_wrapper(int a, int b)
1138     {
1139         lua_callback(a, b);
1140     }
1142     void set_callback_wrapper(const functor<void>& f)
1143     {
1144         lua_callback = f;
1145         set_callback(&callback_wrapper);
1146     }
1148 And then register ``set_callback_wrapper`` instead of registering
1149 ``set_callback``. This will have the effect that when one tries to register the
1150 callback from lua, your ``set_callback_wrapper`` will be called instead and
1151 first set the lua functor to the given function. It will then call the real
1152 ``set_callback`` with the ``callback_wrapper``. The ``callback_wrapper`` will
1153 be called whenever the callback should be called, and it will simply call the
1154 lua function that we registered.
1156 You can also use ``object_cast`` to cast an object to a functor.
1158 ``reset`` on ``functor`` will invalidate the functor (and remove any references
1159 to its lua value). If the functor object has longer lifetime than the lua state
1160 (e.g. if it's a global).
1163 Defining classes in lua
1164 =======================
1166 In addition to binding C++ functions and classes with lua, luabind also provide
1167 an OO-system in lua. ::
1169     class 'lua_testclass'
1171     function lua_testclass:__init(name)
1172         self.name = name
1173     end
1175     function lua_testclass:print()
1176         print(self.name)
1177     end
1179     a = lua_testclass('example')
1180     a:print()
1183 Inheritance can be used between lua-classes::
1185     class 'derived' (lua_testclass)
1187     function derived:__init() super('derived name')
1188     end
1190     function derived:print()
1191         print('Derived:print() -> ')
1192         lua_testclass.print(self)
1193     end
1195 Here the ``super`` keyword is used in the constructor to initialize the base
1196 class. The user is required to call ``super`` first in the constructor.
1198 As you can see in this example, you can call the base class member functions.
1199 You can find all member functions in the base class, but you will have to give
1200 the this-pointer (``self``) as first argument.
1203 Deriving in lua
1204 ---------------
1206 It is also possible to derive lua classes from C++ classes, and override
1207 virtual functions with lua functions. To do this we have to create a wrapper
1208 class for our C++ base class. This is the class that will hold the lua object
1209 when we instantiate a lua class.
1211 The wrapper class has to provide the same constructors as the base class, with
1212 the addition of one extra parameter: ``luabind::weak_ref``. This is the reference
1213 to the lua object that should be held by the wrapper, and should be stored in a
1214 member variable as done in the sample below. ::
1216     class base
1217     {
1218     public:
1219         base(const char* s)
1220         { std::cout << s << "\n"; }
1222         virtual void f(int a) 
1223         { std::cout << "f(" << a << ")\n"; }
1224     };
1226     struct base_wrapper : base
1227     {
1228         weak_ref self;
1229         base_wrapper(weak_ref self_, const char* s)
1230             : base(s), self(self_) 
1231         {}
1233         virtual void f(int a) 
1234         { 
1235             call_member<void>(self, "f", a); 
1236         }
1238         static void f_static(base* ptr, int a)
1239         {
1240             return ptr->base::f(a);
1241         }
1242     };
1244     ...
1246     module(L)
1247     [
1248         class_<base, base_wrapper>("base")
1249             .def(constructor<const char*>())
1250             .def("f", &base_wrapper::f_static)
1251     ];  
1253 Note that if you have both base classes and a base class wrapper, you must give
1254 both bases and the base class wrapper type as template parameter to 
1255 ´´class_´´. The order in which you specify them is not important.
1257 If we didn't have a class wrapper, it would not be possible to pass a lua class
1258 back to C++. Since the entry points of the virtual functions would still point
1259 to the C++ base class, and not to the functions defined in lua. That's why we
1260 need one function that calls the base class' real function (used if the lua
1261 class doesn't redefine it) and one virtual function that dispatches the call
1262 into luabind, to allow it to select if a lua function should be called, or if
1263 the original function should be called. If you don't intend to derive from a
1264 C++ class, or if it doesn't have any virtual member functions, you can register
1265 it without a class wrapper.
1267 You don't need to have a class wrapper in order to derive from a class, but if
1268 it has virtual functions you may have silent errors. 
1270 .. Unnecessary? The rule of thumb is: 
1271   If your class has virtual functions, create a wrapper type, if it doesn't
1272   don't create a wrapper type.
1275 Overloading operators
1276 ---------------------
1278 You can overload most operators in lua for your classes. You do this by simply
1279 declaring a member function with the same name as an operator (the name of the
1280 metamethods in lua). The operators you can overload are:
1282  - __add 
1283  - __sub 
1284  - __mul 
1285  - __div 
1286  - __pow 
1287  - __lt 
1288  - __le 
1289  - __eq 
1290  - __call 
1291  - __unm 
1292  - __tostring
1294 ``__tostring`` isn't really an operator, but it's the metamethod that is called
1295 by the standard library's ``tostring()`` function. There's one strange behavior
1296 regarding binary operators. You are not guaranteed that the self pointer you
1297 get actually refers to an instance of your class. This is because lua doesn't
1298 distinguish the two cases where you get the other operand as left hand value or
1299 right hand value. Consider the following examples::
1301     class 'my_class'
1303       function my_class:__init(v)
1304           self.val = v
1305       end
1306         
1307       function my_class:__sub(v)
1308           return my_class(self.val - v.val)
1309       end
1311       function my_class:__tostring()
1312           return self.val
1313       end
1315 This will work well as long as you only subtracts instances of my_class with
1316 each other. But If you want to be able to subtract ordinary numbers from your
1317 class too, you have to manually check the type of both operands, including the
1318 self object. ::
1320     function my_class:__sub(v)
1321         if (type(self) == 'number') then
1322             return my_class(self - v.val)
1324         elseif (type(v) == 'number') then
1325             return my_class(self.val - v)
1326         
1327         else
1328             -- assume both operands are instances of my_class
1329             return my_class(self.val - v.val)
1331         end
1332     end
1334 The reason why ``__sub`` is used as an example is because subtraction is not
1335 commutative (the order of the operands matter). That's why luabind cannot
1336 change order of the operands to make the self reference always refer to the
1337 actual class instance.
1339 If you have two different lua classes with an overloaded operator, the operator
1340 of the right hand side type will be called. If the other operand is a C++ class
1341 with the same operator overloaded, it will be prioritized over the lua class'
1342 operator. If none of the C++ overloads matches, the lua class operator will be
1343 called.
1346 Finalizers
1347 ----------
1349 If an object needs to perform actions when it's collected we provide a
1350 ``__finalize`` function that can be overridden in lua-classes. The
1351 ``__finalize`` functions will be called on all classes in the inheritance
1352 chain, starting with the most derived type. ::
1354     ...
1356     function lua_testclass:__finalize()
1357         -- called when the an object is collected
1358     end
1361 Exceptions
1362 ==========
1364 If any of the functions you register throws an exception when called, that
1365 exception will be caught by luabind and converted to an error string and
1366 ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
1367 ``const char*`` the string that is pushed on the lua stack, as error message,
1368 will be the string returned by ``std::exception::what()`` or the string itself
1369 respectively. If the exception is unknown, a generic string saying that the
1370 function threw an exception will be pushed.
1372 Exceptions thrown from user defined functions have to be caught by luabind. If
1373 they weren't they would be thrown through lua itself, which is usually compiled
1374 as C code and doesn't support the stack-unwinding that exceptions imply.
1376 Any function that invokes lua code may throw ``luabind::error``. This exception
1377 means that a lua run-time error occurred. The error message is found on top of
1378 the lua stack. The reason why the exception doesn't contain the error string
1379 itself is because it would then require heap allocation which may fail. If an
1380 exception class throws an exception while it is being thrown itself, the
1381 application will be terminated.
1383 Error's synopsis is::
1385     class error : public std::exception
1386     {
1387     public:
1388         error(lua_State*);
1389         lua_State* state() const throw();
1390         virtual const char* what() const throw();
1391     };
1393 The state function returns a pointer to the lua state in which the error was
1394 thrown. This pointer may be invalid if you catch this exception after the lua
1395 state is destructed. If the lua state is valid you can use it to retrieve the
1396 error message from the top of the lua stack.
1398 An example of where the lua state pointer may point to an invalid state
1399 follows::
1401     struct lua_state
1402     {
1403         lua_state(lua_State* L): m_L(L) {}
1404         ~lua_state() { lua_close(m_L); }
1405         operator lua_State*() { return m_L; }
1406         lua_State* m_L;
1407     };
1409     int main()
1410     {
1411         try
1412         {
1413             lua_state L = lua_open();
1414             /* ... */
1415         }
1416         catch(luabind::error& e)
1417         {
1418             lua_State* L = e.state();
1419             // L will now point to the destructed
1420             // lua state and be invalid
1421             /* ... */
1422         }
1423     }
1425 There's another exception that luabind may throw: ``luabind::cast_failed``,
1426 this exception is thrown from ``call_function<>``, ``call_member<>`` or when
1427 ``functor<>`` is invoked. It means that the return value from the lua function
1428 couldn't be converted to a C++ value. It is also thrown from ``object_cast<>``
1429 if the cast cannot be made.
1431 The synopsis for ``luabind::cast_failed`` is::
1433     class cast_failed : public std::exception
1434     {
1435     public:
1436         cast_failed(lua_State*);
1437         lua_State* state() const throw();
1438         LUABIND_TYPE_INFO info() const throw();
1439         virtual const char* what() const throw();
1440     };
1442 Again, the state member function returns a pointer to the lua state where the
1443 error occurred. See the example above to see where this pointer may be invalid.
1445 The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
1446 defaults to a ``const std::type_info*``. This type info describes the type that
1447 we tried to cast a lua value to.
1449 If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
1450 thrown, instead you can set two callback functions that are called instead.
1451 These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
1455     luabind::set_error_callback(void(*)(lua_State*))
1457 The function you set will be called when a runtime-error occur in lua code. You
1458 can find an error message on top of the lua stack. This function is not
1459 expected to return, if it does luabind will call ``std::terminate()``.
1463     luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1465 The function you set is called instead of throwing ``cast_failed``. This function
1466 is not expected to return, if it does luabind will call ``std::terminate()``.
1469 Policies
1470 ========
1472 Sometimes it is necessary to control how luabind passes arguments and return
1473 value, to do this we have policies. These are the policies that can be used:
1475 Copy
1476 ----
1478 This will make a copy of the parameter. This is the default behavior when
1479 passing parameters by-value. Note that this can only be used when passing from
1480 C++ to lua. This policy requires that the parameter type has a copy
1481 constructor.
1483 To use this policy you need to include ``luabind/copy_policy.hpp``.
1486 Adopt
1487 -----
1489 This will transfer ownership of the parameter.
1491 Consider making a factory function in C++ and exposing it to lua::
1493     base* create_base()
1494     {
1495         return new base();
1496     }
1498     ...
1500     module(L)
1501     [
1502         def("create_base", create_base)
1503     ];
1505 Here we need to make sure lua understands that it should adopt the pointer
1506 returned by the factory-function. This can be done using the adopt-policy.
1510     module(L)
1511     [
1512         def(L, "create_base", adopt(return_value))
1513     ];
1515 To specify multiple policies we just separate them with '+'.
1519     base* set_and_get_new(base* ptr)
1520     {
1521         base_ptrs.push_back(ptr);
1522         return new base();
1523     }
1525     module(L)
1526     [
1527         def("set_and_get_new", &set_and_get_new, 
1528             adopt(return_value) + adopt(_1))
1529     ];
1531 When lua adopts a pointer, it will call delete on it. This means that it cannot
1532 adopt pointers allocated with another allocator than new (no malloc for
1533 example).
1535 To use this policy you need to include ``luabind/adopt_policy.hpp``.
1538 Dependency
1539 ----------
1541 The dependency policy is used to create life-time dependencies between values.
1542 Consider the following example::
1544     struct A
1545     {
1546         B member;
1548         const B& get_member()
1549         {
1550             return member;
1551         }
1552     };
1554 When wrapping this class, we would do something like::
1556     module(L)
1557     [
1558         class_<A>("A")
1559             .def(constructor<>())
1560             .def("get_member", &A::get_member)
1561     ];
1564 However, since the return value of get_member is a reference to a member of A,
1565 this will create some life-time issues. For example::
1567     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1568     a = A()
1569     b = a:get_member() -- b points to a member of a
1570     a = nil
1571     collectgarbage(0)  -- since there are no references left to a, it is
1572                        -- removed
1573                        -- at this point, b is pointing into a removed object
1575 When using the dependency-policy, it is possible to tell luabind to tie the
1576 lifetime of one object to another, like this::
1578     module(L)
1579     [
1580         class_<A>("A")
1581             .def(constructor<>())
1582             .def("get_member", &A::get_member, dependency(result, self))
1583     ];
1585 This will create a dependency between the return-value of the function, and the
1586 self-object. This means that the self-object will be kept alive as long as the
1587 result is still alive. ::
1589     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1590     a = A()
1591     b = a:get_member() -- b points to a member of a
1592     a = nil
1593     collectgarbage(0)  -- a is dependent on b, so it isn't removed
1594     b = nil
1595     collectgarbage(0)  -- all dependencies to a gone, a is removed
1597 To use this policy you need to include ``luabind/dependency_policy.hpp``.
1600 Return reference to
1601 -------------------
1603 It is very common to return references to arguments or the this-pointer to
1604 allow for chaining in C++.
1608     struct A
1609     {
1610         float val;
1612         A& set(float v)
1613         {
1614             val = v;
1615             return *this;
1616         }
1617     };
1619 When luabind generates code for this, it will create a new object for the
1620 return-value, pointing to the self-object. This isn't a problem, but could be a
1621 bit inefficient. When using the return_reference_to-policy we have the ability
1622 to tell luabind that the return-value is already on the lua stack.
1626     module(L)
1627     [
1628         class_<A>("A")
1629             .def(constructor<>())
1630             .def("set", &A::set, return_reference_to(self))
1631     ];
1633 Instead of creating a new object, luabind will just copy the object that is
1634 already on the stack.
1636 .. warning:: 
1637    This policy ignores all type information and should be used only it 
1638    situations where the parameter type is a perfect match to the 
1639    return-type (such as in the example).
1641 To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
1644 Out value
1645 ---------
1647 This policy makes it possible to wrap functions that take non const references
1648 as its parameters with the intention to write return values to them.
1652     void f(float& val) { val = val + 10.f; }
1658     void f(float* val) { *val = *val + 10.f; }
1660 Can be wrapped by doing::
1662     module(L)
1663     [
1664         def("f", &f, out_value(_1))
1665     ];
1667 When invoking this function from lua it will return the value assigned to its 
1668 parameter.
1672     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1673     > a = f(10)
1674     > print(a)
1675     20
1677 When this policy is used in conjunction with user define types we often need 
1678 to do ownership transfers.
1682     struct A;
1684     void f1(A*& obj) { obj = new A(); }
1685     void f2(A** obj) { *obj = new A(); }
1687 Here we need to make sure luabind takes control over object returned, for 
1688 this we use the adopt policy::
1690     module(L)
1691     [
1692         class_<A>("A"),
1693         def("f1", &f1, out_value(_1, adopt(_2)))
1694         def("f2", &f2, out_value(_1, adopt(_2)))
1695     ];
1697 Here we are using adopt as an internal policy to out_value. The index 
1698 specified, _2, means adopt will be used to convert the value back to lua. 
1699 Using _1 means the policy will be used when converting from lua to C++.
1701 To use this policy you need to include ``luabind/out_value_policy.hpp``.
1703 Pure out value
1704 --------------
1706 This policy works in exactly the same way as out_value, except that it 
1707 replaces the parameters with default-constructed objects.
1711     void get(float& x, float& y)
1712     {
1713         x = 3.f;
1714         y = 4.f;
1715     }
1717     ...
1719     module(L)
1720     [
1721         def("get", &get, 
1722             pure_out_value(_1) + pure_out_value(_2))
1723     ];
1727     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1728     > x, y = get()
1729     > print(x, y)
1730     3    5
1732 Like out_value, it is possible to specify an internal policy used then 
1733 converting the values back to lua.
1737     void get(test_class*& obj)
1738     {
1739         obj = new test_class();
1740     }
1742     ...
1744     module(L)
1745     [
1746         def("get", &get, pure_out_value(_1, adopt(_1)))
1747     ];
1750 Discard result
1751 --------------
1753 This is a very simple policy which makes it possible to throw away 
1754 the value returned by a C++ function, instead of converting it to 
1755 lua. This example makes sure the this reference never gets converted 
1756 to lua.
1760     struct simple
1761     {
1762         simple& set_name(const std::string& n)
1763         {
1764             name = n;
1765             return *this;
1766         }
1768         std::string name;
1769     };
1771     ...
1773     module(L)
1774     [
1775         class_<simple>("simple")
1776             .def("set_name", &simple::set_name, discard_result)
1777     ];
1779 To use this policy you need to include ``luabind/discard_result_policy.hpp``.
1782 Return STL iterator
1783 -------------------
1785 This policy converts an STL container to a generator function that can be used
1786 in lua to iterate over the container. It works on any container that defines
1787 ``begin()`` and ``end()`` member functions (they have to return iterators). It
1788 can be used like this::
1790     struct A
1791     {
1792         std::vector<std::string> names;
1793     };
1796     module(L)
1797     [
1798         class_<A>("A")
1799             .def_readwrite("names", &A::names, return_stl_iterator)
1800     ];
1802 The lua code to iterate over the container::
1804     a = A()
1806     for name in a.names do
1807       print(name)
1808     end
1811 To use this policy you need to include ``luabind/iterator_policy.hpp``.
1814 Yield
1815 -----    
1817 This policy will cause the function to always yield the current thread when 
1818 returning. See the lua manual for restrictions on yield.
1821 Splitting up the registration
1822 =============================
1824 a.cpp::
1826     luabind::scope register_a()
1827     {
1828         return 
1829             class_<a>("a")
1830                 .def("f", &a::f)
1831                 ;
1832     }
1834 b.cpp::
1836     luabind::scope register_b()
1837     {
1838         return 
1839             class_<b>("b")
1840                 .def("g", &b::g)
1841                 ;
1842     }
1844 module_ab.cpp::
1846     luabind::scope register_a();
1847     luabind::scope register_b();
1849     void register_module(lua_State* L)
1850     {
1851         module("b", L)
1852         [
1853             register_a(),
1854             register_b()
1855         ];
1856     }
1859 Configuration
1860 =============
1862 As mentioned in the `Lua documentation`_, it is possible to pass an
1863 error handler function to ``lua_pcall()``. Luabind makes use of 
1864 ``lua_pcall()`` internally when calling methods and functions. It is
1865 possible to set the error handler function that Luabind will use 
1866 globally::
1868     typedef void(*pcall_callback_fun)(lua_State*);
1869     void set_pcall_callback(pcall_callback_fun fn);
1871 This is primarily useful for adding more information to the error message
1872 returned by a failed protected call.
1874 .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
1876 Build options
1877 -------------
1879 There are a number of configuration options available when building luabind.
1880 It is very important that your project has the exact same conmfiguration 
1881 options as the ones given when the library was build! The exceptions are the
1882 ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based 
1883 options and only matters when you use the library (which means they can 
1884 differ from the settings of the library).
1886 The default settings which will be used if no other settings are given
1887 can be found in ``luabind/config.hpp``.
1889 If you want to change the settings of the library, you can modify the 
1890 config file. It is included and used by all makefiles. You can change paths
1891 to lua and boost in there as well.
1893 LUABIND_MAX_ARITY
1894     Controls the maximum arity of functions that are registered with luabind. 
1895     You can't register functions that takes more parameters than the number 
1896     this macro is set to. It defaults to 5, so, if your functions have greater 
1897     arity you have to redefine it. A high limit will increase compilation time.
1899 LUABIND_MAX_BASES
1900     Controls the maximum number of classes one class can derive from in 
1901     luabind (the number of classes specified within ``bases<>``). 
1902     ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase 
1903     compilation time.
1905 LUABIND_NO_ERROR_CHECKING
1906     If this macro is defined, all the lua code is expected only to make legal 
1907     calls. If illegal function calls are made (e.g. giving parameters that 
1908     doesn't match the function signature) they will not be detected by luabind
1909     and the application will probably crash. Error checking could be disabled 
1910     when shipping a release build (given that no end-user has access to write 
1911     custom lua code). Note that function parameter matching will be done if a 
1912     function is overloaded, since otherwise it's impossible to know which one 
1913     was called. Functions will still be able to throw exceptions when error 
1914     checking is disabled.
1916     If a functions throws an exception it will be caught by luabind and 
1917     propagated with ``lua_error()``.
1919 LUABIND_NO_EXCEPTIONS
1920     This define will disable all usage of try, catch and throw in luabind. 
1921     This will in many cases disable run-time errors, when performing invalid 
1922     casts or calling lua functions that fails or returns values that cannot 
1923     be converted by the given policy. luabind requires that no function called 
1924     directly or indirectly by luabind throws an exception (throwing exceptions 
1925     through lua has undefined behavior).
1927     Where exceptions are the only way to get an error report from luabind, 
1928     they will be replaced with calls to the callback functions set with
1929     ``set_error_callback()`` and ``set_cast_failed_callback()``.
1931 LUA_API
1932     If you want to link dynamically against lua, you can set this define to 
1933     the import-keyword on your compiler and platform. On windows in devstudio 
1934     this should be ``__declspec(dllimport)`` if you want to link against lua 
1935     as a dll.
1937 LUABIND_EXPORT, LUABIND_IMPORT
1938     If you want to link against luabind as a dll (in devstudio), you can 
1939     define ``LUABIND_EXPORT`` to ``__declspec(dllexport)`` and 
1940     ``LUABIND_IMPORT`` to ``__declspec(dllimport)``. 
1941     Note that you have to link against lua as a dll aswell, to make it work.
1943 LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO
1944     If you don't want to use the RTTI supplied by C++ you can supply your own 
1945     type-info structure with the ``LUABIND_TYPE_INFO`` define. Your type-info 
1946     structure must be copyable and must be able to compare itself against 
1947     other type-info structures. You supply the compare function through the 
1948     ``LUABIND_TYPE_INFO_EQUAL()`` define. It should compare the two type-info 
1949     structures it is given and return true if they represent the same type and
1950     false otherwise. You also have to supply a function to generate your 
1951     type-info structure. You do this through the ``LUABIND_TYPEID()`` define. 
1952     It should return your type-info structure and it takes a type as its 
1953     parameter. That is, a compile time parameter. 
1954     ``LUABIND_INVALID_TYPE_INFO`` macro should be defined to an invalid type. 
1955     No other type should be able to produce this type info. To use it you 
1956     probably have to make a traits class with specializations for all classes 
1957     that you have type-info for. Like this::
1959         class A;
1960         class B;
1961         class C;
1963         template<class T> struct typeinfo_trait;
1965         template<> struct typeinfo_trait<A> { enum { type_id = 0 }; };
1966         template<> struct typeinfo_trait<B> { enum { type_id = 1 }; };
1967         template<> struct typeinfo_trait<C> { enum { type_id = 2 }; };
1969     If you have set up your own RTTI system like this (by using integers to
1970     identify types) you can have luabind use it with the following defines::
1972         #define LUABIND_TYPE_INFO const std::type_info*
1973         #define LUABIND_TYPEID(t) &typeid(t)
1974         #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
1975         #define LUABIND_INVALID_TYPE_INFO &typeid(detail::null_type)
1977     Currently the type given through ``LUABIND_TYPE_INFO`` must be less-than 
1978     comparable!
1980 NDEBUG
1981     This define will disable all asserts and should be defined in a release 
1982     build.
1985 Implementation notes
1986 ====================
1988 The classes and objects are implemented as user data in lua. To make sure that
1989 the user data really is the internal structure it is supposed to be, we tag
1990 their metatables. A user data who's metatable contains a boolean member named
1991 ``__luabind_classrep`` is expected to be a class exported by luabind. A user
1992 data who's metatable contains a boolean member named ``__luabind_class`` is
1993 expected to be an instantiation of a luabind class.
1995 This means that if you make your own user data and tags its metatable with the
1996 exact same names, you can very easily fool luabind and crash the application.
1998 In the lua registry, luabind keeps an entry called ``__luabind_classes``. It
1999 should not be removed or overwritten.
2001 In the global table, a variable called ``super`` is used every time a
2002 constructor in a lua-class is called. This is to make it easy for that
2003 constructor to call its base class' constructor. So, if you have a global
2004 variable named super it may very well be overwritten. This is probably not the
2005 best solution, and this restriction may very well be removed in the future.
2007 Luabind uses two upvalues for functions that it registers. The first is a
2008 userdata containing a list of overloads for the function, the other is a light
2009 userdata with the value 0x1337, this last value is used to identify functions
2010 registered by luabind. It should be virtually impossible to have such a pointer
2011 as secondary upvalue by pure chance. This means, if you are trying to replace
2012 an existing function with a luabind function, luabind will see that the
2013 secondary upvalue isn't the magic id number and replace it. If it can identify
2014 the function to be a luabind function, it won't replace it, but rather add
2015 another overload to it.
2017 Inside the luabind namespace, there's another namespace called detail. This
2018 namespace contains non-public classes and are not supposed to be used directly.
2021 Error messages
2022 ==============
2024 - `the attribute '<class-name>.<attribute-name>' is read only`
2026       There is no data member named <attribute-name> in the class <class-name>,
2027       or there's no setter-method registered on that property name. See the 
2028       properties section.
2030 -  `the attribute '<class-name>.<attribute-name>' is of type: (<class-name>)
2031    and does not match (<class_name>)`
2033        This error is generated if you try to assign an attribute with a value 
2034        of a type that cannot be converted to the attribute's type.
2036 - `<class-name>() threw an exception, <class-name>:<function-name>() threw an 
2037   exception`
2039         The class' constructor or member function threw an unknown exception.
2040         Known exceptions are const char*, std::exception. See the 
2041         `exceptions`_ section.
2043 - `no overload of '<class-name>:<function-name>' matched the arguments 
2044   (<parameter-types>)`
2045 - `no match for function call '<function-name>' with the parameters 
2046   (<parameter-types>)`
2047 - `no constructor of <class-name> matched the arguments (<parameter-types>)`
2048 - `no operator <operator-name> matched the arguments (<parameter-types>)`
2050        No function/operator with the given name takes the parameters you gave 
2051        it. You have either misspelled the function name, or given it incorrect
2052        parameters. This error is followed by a list of possible candidate 
2053        functions to help you figure out what parameter has the wrong type. If
2054        the candidate list is empty there's no function at all with that name.
2055        See the signature matching section.
2057 - `call of overloaded '<class-name>:<function-name>(<parameter-types>)' is 
2058   ambiguous`
2059 - `ambiguous match for function call '<function-name>' with the parameters 
2060   (<parameter-types>)`
2061 - `call of overloaded constructor '<class-name>(<parameter-types>)' is 
2062   ambiguous`
2063 - `call of overloaded operator <operator-name> (<parameter-types>) is 
2064   ambiguous`
2066     This means that the function/operator you are trying to call has at least
2067     one other overload that matches the arguments just as good as the first
2068     overload.
2070 - `cannot derive from C++ class '<class-name>'. It does not have a wrapped
2071   type.`
2073     You are trying to derive a lua class from a C++ class that doesn't have a
2074     wrapped type. You have to give your C++ class a wrapped type when you 
2075     register it with lua. See the deriving in lua section.
2077 - `derived class must call super on base`
2078 - `cannot set property '<class-name>.<attribute_name>' because it's read only`
2080     The attribute you are trying to set is registered as read only. If you want
2081     it to be writeable you have to change your class registration and use
2082     def_readwrite() instead of def_readonly(). Alternatively (if your 
2083     attribute is a property with getter and setter functions), you have to 
2084     give a setter function when declaring your attribute. See the properties section.
2086 - `no static '<enum-name>' in class '<class-name>'`
2088     You will get this error message if you are trying to access an enum that
2089     doesn't exist. Read about how to declare enums.
2091 - `expected base class`
2093     You have written a malformed class definition in lua. The format is: class
2094     '<class-name>' [<base-class>]. If you don't want to derive from a base 
2095     class, you have to break the line directly after the class declaration.
2097 - `invalid construct, expected class name`
2099     You have written a malformed class definition in lua. The class function
2100     expects a string as argument. That string is the name of the lua class to
2101     define.
2107 What's up with __cdecl and __stdcall? 
2108     If you're having problem with functions
2109     that cannot be converted from 'void (__stdcall *)(int,int)' to 'void 
2110     (__cdecl*)(int,int)'. You can change the project settings to make the
2111     compiler generate functions with __cdecl calling conventions. This is 
2112     a problem in developer studio.
2114 What's wrong with functions taking variable number of arguments?
2115     You cannot register a function with ellipses in its signature. Since 
2116     ellipses don't preserve type safety, those should be avoided anyway.
2118 Internal structure overflow in VC
2119     If you, in visual studio, get fatal error C1204: compiler limit : 
2120     internal structure overflow. You should try to split that compilation 
2121     unit up in smaller ones.
2123 What's wrong with precompiled headers in VC?
2124     Visual Studio doesn't like anonymous namespaces in its precompiled 
2125     headers. If you encounter this problem you can disable precompiled 
2126     headers for the compilation unit (cpp-file) that uses luabind.
2128 error C1076: compiler limit - internal heap limit reached in VC
2129     In visual studio you will probably hit this error. To fix it you have to
2130     increase the internal heap with a command-line option. We managed to
2131     compile the test suit with /Zm300, but you may need a larger heap then 
2132     that.
2134 error C1055: compiler limit : out of keys in VC
2135     It seems that this error occurs when too many assert() are used in a
2136     program, or more specifically, the __LINE__ macro. It seems to be fixed by
2137     changing /ZI (Program database for edit and continue) to /Zi 
2138     (Program database).
2140 How come my executable is huge?
2141     If you're compiling in debug mode, you will probably have a lot of
2142     debug-info and symbols (luabind consists of a lot of functions). Also, 
2143     if built in debug mode, no optimizations were applied, luabind relies on 
2144     that the compiler is able to inline functions. If you built in release 
2145     mode, try running strip on your executable to remove export-symbols, 
2146     this will trim down the size.
2148     Our tests suggests that cygwin's gcc produces much bigger executables 
2149     compared to gcc on other platforms and other compilers.
2151 .. HUH?! // check the magic number that identifies luabind's functions 
2153 Can I register class templates with luabind?
2154     Yes you can, but you can only register explicit instantiations of the 
2155     class. Because there's no lua counterpart to C++ templates. For example, 
2156     you can register an explicit instantiation of std::vector<> like this::
2158         module(L)
2159         [
2160             class_<std::vector<int> >("vector")
2161                 .def(constructor<int>)
2162                 .def("push_back", &std::vector<int>::push_back)
2163         ];
2165 .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
2167 Do I have to register destructors for my classes?
2168     No, the destructor of a class is always called by luabind when an 
2169     object is collected. Note that lua has to own the object to collect it.
2170     If you pass it to C++ and gives up ownership (with adopt policy) it will 
2171     no longer be owned by lua, and not collected.
2173     If you have a class hierarchy, you should make the destructor virtual if 
2174     you want to be sure that the correct destructor is called (this apply to C++ 
2175     in general).
2177 .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ.
2179 Fatal Error C1063 compiler limit : compiler stack overflow in VC
2180     VC6.5 chokes on warnings, if you are getting alot of warnings from your 
2181     code try suppressing them with a pragma directive, this should solve the 
2182     problem.
2184 Crashes when linking against luabind as a dll in windows
2185     When you build luabind, lua and you project, make sure you link against 
2186     the runtime dynamically (as a dll).
2188 I cannot register a function with a non-const parameter
2189     This is because there is no way to get a reference to a lua value. Have 
2190     a look at out_value and pure_out_value policies.
2193 Known issues
2194 ============
2196 - You cannot use strings with extra nulls in them as member names that refers
2197   to C++ members. 
2199 - If one class registers two functions with the same name and the same 
2200   signature, there's currently no error. The last registered function will 
2201   be the one that's used. 
2203 - In vc7, classes can not be called test. 
2205 .. remove? - Visual studio have problems selecting the correct overload of std::swap() 
2206   for luabind::object. 
2208 - If you register a function and later rename it, error messages will use the 
2209   original function name.
2212 Acknowledgments
2213 ===============
2215 This library was written by Daniel Wallin and Arvid Norberg. © Copyright 2003. 
2216 All rights reserved.
2218 This library was inspired by Dave Abrahams' Boost.Python library which can be 
2219 found in the boost_ library.
2221 Evan Wies has contributed with thorough testing and countless bug reports and
2222 feature ideas.
2224 Thanks to Umeå university for providing development and testing hardware.