Fixed for VC6.5.
[luabind.git] / doc / docs.rst
blob8f81b1261c9424862292b9178a56966917ecb1af
1 +++++++++
2  luabind
3 +++++++++
5 :Author: Daniel Wallin, Arvid Norberg
6 :Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.
7 :Date: $Date$
8 :Revision: $Revision$
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.
122 Building luabind
123 ================
125 To keep down the compilation-time luabind is built as a library. This means you
126 have to either build it and link against it, or include its source files in
127 your project. You also have to make sure the luabind directory is somewhere in
128 your compiler's include path. It requires `Boost`_ 1.32.0 or 1.33.0 to be
129 installed (only boost headers). It also requires that Lua is installed.
131 The official way of building luabind is with `Boost.Build V2`_. To properly build
132 luabind with Boost.Build you need to set two environment variables:
134 BOOST_ROOT
135     Point this to your Boost installation.
137 LUA_PATH
138     Point this to your Lua directory. The build system will assume that the
139     include and library files are located in ``$(LUA_PATH)/include/`` and
140     ``$(LUA_PATH)/lib/.``
142 For backward compatibility, there is also a makefile in the root-directory that
143 will build the library and the test programs. If you are using a UNIX-system (or
144 cygwin) they will make it easy to build luabind as a static library. If you are
145 using Visual Studio it may be easier to include the files in the src directory
146 in your project.
148 When building luabind you have several options that may streamline the library
149 to better suit your needs. It is extremely important that your application has
150 the same settings as the library was built with. The available options are
151 found in the `Configuration`_ section.
153 If you want to change the settings to differ from the default, it's recommended
154 that you define the settings on the command line of all your files (in the
155 project settings in visual studio).
157 .. _`Boost.Build V2`: http://www.boost.org/tools/build/v2/index_v2.html
160 Basic usage
161 ===========
163 To use luabind, you must include ``lua.h`` and luabind's main header file::
165     extern "C"
166     {
167         #include "lua.h"
168     }
170     #include <luabind/luabind.hpp>
172 This includes support for both registering classes and functions. If you just
173 want to have support for functions or classes you can include
174 ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
176     #include <luabind/function.hpp>
177     #include <luabind/class.hpp>
179 The first thing you need to do is to call ``luabind::open(lua_State*)`` which
180 will register the functions to create classes from Lua, and initialize some
181 state-global structures used by luabind. If you don't call this function you
182 will hit asserts later in the library. There is no corresponding close function
183 because once a class has been registered in Lua, there really isn't any good
184 way to remove it. Partly because any remaining instances of that class relies
185 on the class being there. Everything will be cleaned up when the state is
186 closed though.
188 .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
190 Luabind's headers will never include ``lua.h`` directly, but through
191 ``<luabind/lua_include.hpp>``. If you for some reason need to include another
192 Lua header, you can modify this file.
195 Hello world
196 -----------
200     #include <iostream>
201     #include <luabind/luabind.hpp>
203     void greet()
204     {
205         std::cout << "hello world!\n";
206     }
208     extern "C" int init(lua_State* L)
209     {
210         using namespace luabind;
212         open(L);
214         module(L)
215         [
216             def("greet", &greet)
217         ];
219         return 0;
220     }
224     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
225     > loadlib('hello_world.dll', 'init')()
226     > greet()
227     Hello world!
228     >
230 Scopes
231 ======
233 Everything that gets registered in Lua is registered in a namespace (Lua
234 tables) or in the global scope (called module). All registrations must be
235 surrounded by its scope. To define a module, the ``luabind::module`` class is
236 used. It is used like this::
238     module(L)
239     [
240         // declarations
241     ];
243 This will register all declared functions or classes in the global namespace in
244 Lua. If you want to have a namespace for your module (like the standard
245 libraries) you can give a name to the constructor, like this::
247     module(L, "my_library")
248     [
249         // declarations
250     ];
252 Here all declarations will be put in the my_library table.
254 If you want nested namespace's you can use the ``luabind::namespace_`` class. It
255 works exactly as ``luabind::module`` except that it doesn't take a lua_State*
256 in it's constructor. An example of its usage could look like this::
258     module(L, "my_library")
259     [
260         // declarations
262         namespace_("detail")
263         [
264             // library-private declarations
265         ]
266     ];
268 As you might have figured out, the following declarations are equivalent::
270     module(L)
271     [
272         namespace_("my_library")
273         [
274             // declarations
275         ]
277     ];
280     
281     module(L, "my_library")
282     [
283         // declarations
284     ];
286 Each declaration must be separated by a comma, like this::
288     module(L)
289     [
290         def("f", &f),
291         def("g", &g),
292         class_<A>("A")
293             .def(constructor<int, int>),
294         def("h", &h)
295     ];
298 More about the actual declarations in the `Binding functions to Lua`_ and
299 `Binding classes to Lua`_ sections.
301 A word of caution, if you are in really bad need for performance, putting your
302 functions in tables will increase the lookup time.
305 Binding functions to Lua
306 ========================
308 To bind functions to Lua you use the function ``luabind::def()``. It has the
309 following synopsis::
311     template<class F, class policies>
312     void def(const char* name, F f, const Policies&);
314 - name is the name the function will have within Lua. 
315 - F is the function pointer you want to register. 
316 - The Policies parameter is used to describe how parameters and return values 
317   are treated by the function, this is an optional parameter. More on this in 
318   the `policies`_ section.
320 An example usage could be if you want to register the function ``float
321 std::sin(float)``::
323     module(L)
324     [
325         def("sin", &std::sin)
326     ];
328 Overloaded functions
329 --------------------
331 If you have more than one function with the same name, and want to register
332 them in Lua, you have to explicitly give the signature. This is to let C++ know
333 which function you refer to. For example, if you have two functions, ``int
334 f(const char*)`` and ``void f(int)``. ::
336     module(L)
337     [
338         def("f", (int(*)(const char*)) &f),
339         def("f", (void(*)(int)) &f)
340     ];
342 Signature matching
343 ------------------
345 luabind will generate code that checks the Lua stack to see if the values there
346 can match your functions' signatures. It will handle implicit typecasts between
347 derived classes, and it will prefer matches with the least number of implicit
348 casts. In a function call, if the function is overloaded and there's no
349 overload that match the parameters better than the other, you have an
350 ambiguity. This will spawn a run-time error, stating that the function call is
351 ambiguous. A simple example of this is to register one function that takes an
352 int and one that takes a float. Since Lua doesn't distinguish between floats and
353 integers, both will always match.
355 Since all overloads are tested, it will always find the best match (not the
356 first match). This also means that it can handle situations where the only
357 difference in the signature is that one member function is const and the other
358 isn't. 
360 .. sidebar:: Ownership transfer
362    To correctly handle ownership transfer, create_a() would need an adopt
363    return value policy. More on this in the `Policies`_ section.
365 For example, if the following function and class is registered:
368    
369     struct A
370     {
371         void f();
372         void f() const;
373     };
375     const A* create_a();
377     struct B: A {};
378     struct C: B {};
380     void g(A*);
381     void g(B*);
383 And the following Lua code is executed::
385     a1 = create_a()
386     a1:f() -- the const version is called
388     a2 = A()
389     a2:f() -- the non-const version is called
391     a = A()
392     b = B()
393     c = C()
395     g(a) -- calls g(A*)
396     g(b) -- calls g(B*)
397     g(c) -- calls g(B*)
400 Calling Lua functions
401 ---------------------
403 To call a Lua function, you can either use ``call_function()`` or
404 an ``object``.
408     template<class Ret>
409     Ret call_function(lua_State* L, const char* name, ...)
410     template<class Ret>
411     Ret call_function(object const& obj, ...)
413 There are two overloads of the ``call_function`` function, one that calls
414 a function given its name, and one that takes an object that should be a Lua
415 value that can be called as a function.
417 The overload that takes a name can only call global Lua functions. The ...
418 represents a variable number of parameters that are sent to the Lua
419 function. This function call may throw ``luabind::error`` if the function
420 call fails.
422 The return value isn't actually Ret (the template parameter), but a proxy
423 object that will do the function call. This enables you to give policies to the
424 call. You do this with the operator[]. You give the policies within the
425 brackets, like this::
427     int ret = call_function<int>(
428         L 
429       , "a_lua_function"
430       , new complex_class()
431     )[ adopt(_1) ];
433 If you want to pass a parameter as a reference, you have to wrap it with the
434 `Boost.Ref`__.
436 __ http://www.boost.org/doc/html/ref.html
438 Like this::
440         int ret = call_function(L, "fun", boost::ref(val));
443 If you want to use a custom error handler for the function call, see
444 ``set_pcall_callback`` under Configuration_.
446 Using Lua threads
447 -----------------
449 To start a Lua thread, you have to call ``lua_resume()``, this means that you
450 cannot use the previous function ``call_function()`` to start a thread. You have
451 to use
455     template<class Ret>
456     Ret resume_function(lua_State* L, const char* name, ...)
457     template<class Ret>
458     Ret resume_function(object const& obj, ...)
464     template<class Ret>
465     Ret resume(lua_State* L, ...)
467 The first time you start the thread, you have to give it a function to execute. i.e. you
468 have to use ``resume_function``, when the Lua function yields, it will return the first
469 value passed in to ``lua_yield()``. When you want to continue the execution, you just call
470 ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
471 it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side.
473 For yielding C++-functions (without the support of passing data back and forth between the
474 Lua side and the c++ side), you can use the yield_ policy.
476 With the overload of ``resume_function`` that takes an object_, it is important that the
477 object was constructed with the thread as its ``lua_State*``. Like this:
479 .. parsed-literal::
481         lua_State* thread = lua_newthread(L);
482         object fun = get_global(**thread**)["my_thread_fun"];
483         resume_function(fun);
486 Binding classes to Lua
487 ======================
489 To register classes you use a class called ``class_``. Its name is supposed to
490 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
491 member function ``def()`` that is used to register member functions, operators,
492 constructors, enums and properties on the class. It will return its
493 this-pointer, to let you register more members directly.
495 Let's start with a simple example. Consider the following C++ class::
497     class testclass
498     {
499     public:
500         testclass(const std::string& s): m_string(s) {}
501         void print_string() { std::cout << m_string << "\n"; }
503     private:
504         std::string m_string;
505     };
507 To register it with a Lua environment, write as follows (assuming you are using
508 namespace luabind)::
510     module(L)
511     [
512         class_<testclass>("testclass")
513             .def(constructor<const std::string&>())
514             .def("print_string", &testclass::print_string)
515     ];
517 This will register the class with the name testclass and constructor that takes
518 a string as argument and one member function with the name ``print_string``.
522     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
523     > a = testclass('a string')
524     > a:print_string()
525     a string
527 It is also possible to register free functions as member functions. The
528 requirement on the function is that it takes a pointer, const pointer,
529 reference or const reference to the class type as the first parameter. The rest
530 of the parameters are the ones that are visible in Lua, while the object
531 pointer is given as the first parameter. If we have the following C++ code::
533     struct A
534     {
535         int a;
536     };
538     int plus(A* o, int v) { return o->a + v; }
540 You can register ``plus()`` as if it was a member function of A like this::
542     class_<A>("A")
543         .def("plus", &plus)
545 ``plus()`` can now be called as a member function on A with one parameter, int.
546 If the object pointer parameter is const, the function will act as if it was a
547 const member function (it can be called on const objects).
550 Overloaded member functions
551 ---------------------------
553 When binding more than one overloads of a member function, or just binding
554 one overload of an overloaded member function, you have to disambiguate
555 the member function pointer you pass to ``def``. To do this, you can use an
556 ordinary C-style cast, to cast it to the right overload. To do this, you have
557 to know how to express member function types in C++, here's a short tutorial
558 (for more info, refer to your favourite book on C++).
560 The syntax for member function pointer follows:
562 .. parsed-literal::
564     *return-value* (*class-name*::\*)(*arg1-type*, *arg2-type*, *...*)
566 Here's an example illlustrating this::
568     struct A
569     {
570         void f(int);
571         void f(int, int);
572     };
576     class_<A>()
577         .def("f", (void(A::*)(int))&A::f)
579 This selects the first overload of the function ``f`` to bind. The second
580 overload is not bound.
583 Properties
584 ----------
586 To register a global data member with a class is easily done. Consider the
587 following class::
589     struct A
590     {
591         int a;
592     };
594 This class is registered like this::
596     module(L)
597     [
598         class_<A>("A")
599             .def_readwrite("a", &A::a)
600     ];
602 This gives read and write access to the member variable ``A::a``. It is also
603 possible to register attributes with read-only access::
605     module(L)
606     [
607         class_<A>("A")
608             .def_readonly("a", &A::a)
609     ];
611 When binding members that are a non-primitive type, the auto generated getter
612 function will return a reference to it. This is to allow chained .-operators.
613 For example, when having a struct containing another struct. Like this::
615     struct A { int m; };
616     struct B { A a; };
618 When binding ``B`` to lua, the following expression code should work::
620     b = B()
621     b.a.m = 1
622     assert(b.a.m == 1)
624 This requires the first lookup (on ``a``) to return a reference to ``A``, and
625 not a copy. In that case, luabind will automatically use the dependency policy
626 to make the return value dependent on the object in which it is stored. So, if
627 the returned reference lives longer than all references to the object (b in
628 this case) it will keep the object alive, to avoid being a dangling pointer.
630 You can also register getter and setter functions and make them look as if they
631 were a public data member. Consider the following class::
633     class A
634     {
635     public:
636         void set_a(int x) { a = x; }
637         int get_a() const { return a; }
639     private:
640         int a;
641     };
643 It can be registered as if it had a public data member a like this::
645     class_<A>("A")
646         .property("a", &A::get_a, &A::set_a)
648 This way the ``get_a()`` and ``set_a()`` functions will be called instead of
649 just writing  to the data member. If you want to make it read only you can just
650 omit the last parameter. Please note that the get function **has to be
651 const**, otherwise it won't compile. This seems to be a common source of errors.
654 Enums
655 -----
657 If your class contains enumerated constants (enums), you can register them as
658 well to make them available in Lua. Note that they will not be type safe, all
659 enums are integers in Lua, and all functions that takes an enum, will accept
660 any integer. You register them like this::
662     module(L)
663     [
664         class_<A>("A")
665             .enum_("constants")
666             [
667                 value("my_enum", 4),
668                 value("my_2nd_enum", 7),
669                 value("another_enum", 6)
670             ]
671     ];
673 In Lua they are accessed like any data member, except that they are read-only
674 and reached on the class itself rather than on an instance of the class.
678     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
679     > print(A.my_enum)
680     4
681     > print(A.another_enum)
682     6
685 Operators
686 ---------
688 To bind operators you have to include ``<luabind/operator.hpp>``.
690 The mechanism for registering operators on your class is pretty simple. You use
691 a global name ``luabind::self`` to refer to the class itself and then you just
692 write the operator expression inside the ``def()`` call. This class::
694     struct vec
695     {
696         vec operator+(int s);
697     };
699 Is registered like this:
701 .. parsed-literal::
703     module(L)
704     [
705         class_<vec>("vec")
706             .def(**self + int()**)
707     ];
709 This will work regardless if your plus operator is defined inside your class or
710 as a free function.
712 If your operator is const (or, when defined as a free function, takes a const
713 reference to the class itself) you have to use ``const_self`` instead of
714 ``self``. Like this:
716 .. parsed-literal::
718     module(L)
719     [
720         class_<vec>("vec")
721             .def(**const_self** + int())
722     ];
724 The operators supported are those available in Lua:
726 .. parsed-literal::
728     +    -    \*    /    ==    <    <=
730 This means, no in-place operators. The equality operator (``==``) has a little
731 hitch; it will not be called if the references are equal. This means that the
732 ``==`` operator has to do pretty much what's it's expected to do.
734 Lua does not support operators such as ``!=``, ``>`` or ``>=``. That's why you
735 can only register the operators listed above. When you invoke one of the
736 mentioned operators, lua will define it in terms of one of the avaliable
737 operators.
739 In the above example the other operand type is instantiated by writing
740 ``int()``. If the operand type is a complex type that cannot easily be
741 instantiated you can wrap the type in a class called ``other<>``. For example:
743 To register this class, we don't want to instantiate a string just to register
744 the operator.
748     struct vec
749     {
750         vec operator+(std::string);
751     };
753 Instead we use the ``other<>`` wrapper like this:
755 .. parsed-literal::
757     module(L)
758     [
759         class_<vec>("vec")
760             .def(self + **other<std::string>()**)
761     ];
763 To register an application (function call-) operator:
765 .. parsed-literal::
767     module(L)
768     [
769         class_<vec>("vec")
770             .def( **self(int())** )
771     ];
773 There's one special operator. In Lua it's called ``__tostring``, it's not
774 really an operator. It is used for converting objects to strings in a standard
775 way in Lua. If you register this functionality, you will be able to use the lua
776 standard function ``tostring()`` for converting your object to a string.
778 To implement this operator in C++ you should supply an ``operator<<`` for
779 std::ostream. Like this example:
781 .. parsed-literal::
783     class number {};
784     std::ostream& operator<<(std::ostream&, number&);
786     ...
787     
788     module(L)
789     [
790         class_<number>("number")
791             .def(**tostring(self)**)
792     ];
795 Nested scopes and static functions
796 ----------------------------------
798 It is possible to add nested scopes to a class. This is useful when you need 
799 to wrap a nested class, or a static function.
801 .. parsed-literal::
803     class_<foo>("foo")
804         .def(constructor<>()
805         **.scope
806         [
807             class_<inner>("nested"),
808             def("f", &f)
809         ]**;
811 In this example, ``f`` will behave like a static member function of the class
812 ``foo``, and the class ``nested`` will behave like a nested class of ``foo``.
814 It's also possible to add namespace's to classes using the same syntax.
817 Derived classes
818 ---------------
819   
820 If you want to register classes that derives from other classes, you can
821 specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
822 following hierarchy::
823    
824     struct A {};
825     struct B : A {};
827 Would be registered like this::
829     module(L)
830     [
831         class_<A>("A"),
832         class_<B, A>("B")
833     ];
835 If you have multiple inheritance you can specify more than one base. If B would
836 also derive from a class C, it would be registered like this::
838     module(L)
839     [
840         class_<B, bases<A, C> >("B")
841     ];
843 Note that you can omit ``bases<>`` when using single inheritance.
845 .. note::
846    If you don't specify that classes derive from each other, luabind will not
847    be able to implicitly cast pointers between the types.
850 Smart pointers
851 --------------
853 When you register a class you can tell luabind that all instances of that class
854 should be held by some kind of smart pointer (boost::shared_ptr for instance).
855 You do this by giving the holder type as an extra template parameter to
856 the ``class_`` you are constructing, like this::
858     module(L)
859     [
860         class_<A, boost::shared_ptr<A> >("A")
861     ];
863 You also have to supply two functions for your smart pointer. One that returns
864 the type of const version of the smart pointer type (boost::shared_ptr<const A>
865 in this case). And one function that extracts the raw pointer from the smart
866 pointer. The first function is needed because luabind has to allow the
867 non-const -> conversion when passing values from Lua to C++. The second
868 function is needed when Lua calls member functions on held types, the this
869 pointer must be a raw pointer, it is also needed to allow the smart_pointer ->
870 raw_pointer conversion from Lua to C++. They look like this::
872     namespace luabind {
874         template<class T>
875         T* get_pointer(boost::shared_ptr<T>& p) 
876         {
877             return p.get(); 
878         }
880         template<class A>
881         boost::shared_ptr<const A>* 
882         get_const_holder(boost::shared_ptr<A>*)
883         {
884             return 0;
885         }
886     }
888 The second function will only be used to get a compile time mapping
889 of ``boost::shared_ptr<A>`` to its const version,
890 ``boost::shared_ptr<const A>``. It will never be called, so the
891 return value doesn't matter (only the return type).
893 The conversion that works are (given that B is a base class of A):
895 .. topic:: From Lua to C++
897     ========================= ========================
898     Source                    Target
899     ========================= ========================
900     ``holder_type<A>``        ``A*``
901     ``holder_type<A>``        ``B*``
902     ``holder_type<A>``        ``A const*``
903     ``holder_type<A>``        ``B const*``
904     ``holder_type<A>``        ``holder_type<A>``
905     ``holder_type<A>``        ``holder_type<A const>``
906     ``holder_type<A const>``  ``A const*``
907     ``holder_type<A const>``  ``B const*``
908     ``holder_type<A const>``  ``holder_type<A const>``
909     ========================= ========================
911 .. topic:: From C++ to Lua
913     =============================== ========================
914     Source                          Target
915     =============================== ========================
916     ``holder_type<A>``              ``holder_type<A>``
917     ``holder_type<A const>``        ``holder_type<A const>``
918     ``holder_type<A> const&``       ``holder_type<A>``
919     ``holder_type<A const> const&`` ``holder_type<A const>``
920     =============================== ========================
922 When using a holder type, it can be useful to know if the pointer is valid
923 (i.e. not null). For example when using std::auto_ptr, the holder will be
924 invalidated when passed as a parameter to a function. For this purpose there
925 is a member of all object instances in luabind: ``__ok``. ::
927     struct X {};
928     void f(std::auto_ptr<X>);
930     module(L)
931     [
932         class_<X, std::auto_ptr<X> >("X")
933             .def(constructor<>()),
935         def("f", &f)
936     ];
939     
940     Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
941     > a = X()
942     > f(a)
943     > print a.__ok
944     false
947 When registering a hierarchy of classes, where all instances are to be held
948 by a smart pointer, all the classes should have the baseclass' holder type.
949 Like this:
951 .. parsed-literal::
953         module(L)
954         [
955             class_<base, boost::shared_ptr<base> >("base")
956                 .def(constructor<>()),
957             class_<derived, base, **boost::shared_ptr<base>** >("base")
958                 .def(constructor<>())
959         ];
961 Internally, luabind will do the necessary conversions on the raw pointers, which
962 are first extracted from the holder type.
965 Splitting class registrations
966 -----------------------------
968 In some situations it may be desirable to split a registration of a class
969 across different compilation units. Partly to save rebuild time when changing
970 in one part of the binding, and in some cases compiler limits may force you
971 to split it. To do this is very simple. Consider the following sample code::
973     void register_part1(class_<X>& x)
974     {
975         x.def(/*...*/);
976     }
978     void register_part2(class_<X>& x)
979     {
980         x.def(/*...*/);
981     }
983     void register_(lua_State* L)
984     {
985         class_<X> x("x");
987         register_part1(x);
988         register_part2(x);
990         module(L) [ x ];
991     }
993 Here, the class ``X`` is registered in two steps. The two functions
994 ``register_part1`` and ``register_part2`` may be put in separate compilation
995 units.
997 To separate the module registration and the classes to be registered, see
998 `Splitting up the registration`_.
1000 Object
1001 ======
1003 Since functions have to be able to take Lua values (of variable type) we need a
1004 wrapper around them. This wrapper is called ``luabind::object``. If the
1005 function you register takes an object, it will match any Lua value. To use it,
1006 you need to include ``<luabind/object.hpp>``.
1008 .. topic:: Synopsis
1010     .. parsed-literal::
1012         class object
1013         {
1014         public:
1015             template<class T>
1016             object(lua_State\*, T const& value);
1017             object(from_stack const&);
1018             object(object const&);
1019             object();
1021             ~object();
1023             lua_State\* interpreter() const;
1024             void push() const;
1025             bool is_valid() const;
1026             operator *safe_bool_type* () const;
1028             template<class Key>
1029             *implementation-defined* operator[](Key const&);
1031             template<class T>
1032             object& operator=(T const&);
1033             object& operator=(object const&);
1035             bool operator==(object const&) const;
1036             bool operator<(object const&) const;
1037             bool operator<=(object const&) const;
1038             bool operator>(object const&) const;
1039             bool operator>=(object const&) const;
1040             bool operator!=(object const&) const;
1042             template <class T>
1043             *implementation-defined* operator[](T const& key) const
1045             void swap(object&);
1047             *implementation-defined* operator()();
1049             template<class A0>
1050             *implementation-defined* operator()(A0 const& a0);
1052             template<class A0, class A1>
1053             *implementation-defined* operator()(A0 const& a0, A1 const& a1);
1055             /\* ... \*/
1056         };
1058 When you have a Lua object, you can assign it a new value with the assignment
1059 operator (=). When you do this, the ``default_policy`` will be used to make the
1060 conversion from C++ value to Lua. If your ``luabind::object`` is a table you
1061 can access its members through the operator[] or the Iterators_. The value
1062 returned from the operator[] is a proxy object that can be used both for
1063 reading and writing values into the table (using operator=). Note that it is
1064 impossible to know if a Lua value is indexable or not (lua_gettable doesn't
1065 fail, it succeeds or crashes). This means that if you're trying to index
1066 something that cannot be indexed, you're on your own. Lua will call its
1067 ``panic()`` function (you can define your own panic function using
1068 ``lua_setpanicf``). There are also free functions that can be used for
1069 indexing the table, see `Related functions`_.
1071 The constructor that takes a ``from_stack`` object is used when you want to
1072 initialize the object with a value from the lua stack. The ``from_stack``
1073 type has the following constructor::
1075          from_stack(lua_State* L, int index);
1077 The index is an ordinary lua stack index, negative values are indexed from the
1078 top of the stack. You use it like this::
1080          object o(from_stack(L, -1));
1082 This will create the object ``o`` and copy the value from the top of the lua stack.
1084 The ``interpreter()`` function returns the Lua state where this object is stored.
1085 If you want to manipulate the object with Lua functions directly you can push
1086 it onto the Lua stack by calling ``push()``.
1088 The operator== will call lua_equal() on the operands and return its result.
1090 The ``is_valid()`` function tells you whether the object has been initialized
1091 or not. When created with its default constructor, objects are invalid. To make
1092 an object valid, you can assign it a value. If you want to invalidate an object
1093 you can simply assign it an invalid object.
1095 .. So what? implementation detail, leave out of docs
1096   isn't really an implicit cast to bool, but an implicit cast
1097   to a member pointer, since member pointers don't have any arithmetic operators
1098   on them (which can cause hard to find errors). The functionality of the cast
1099   operator
1101 The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
1102 that these snippets are equivalent::
1104     object o;
1105     // ...
1106     if (o)
1107     {
1108         // ...
1109     }
1111     ...
1113     object o;
1114     // ...
1115     if (o.is_valid())
1116     {
1117         // ...
1118     }
1120 The application operator will call the value as if it was a function. You can
1121 give it any number of parameters (currently the ``default_policy`` will be used
1122 for the conversion). The returned object refers to the return value (currently
1123 only one return value is supported). This operator may throw ``luabind::error``
1124 if the function call fails. If you want to specify policies to your function
1125 call, you can use index-operator (operator[]) on the function call, and give
1126 the policies within the [ and ]. Like this::
1128     my_function_object(
1129         2
1130       , 8
1131       , new my_complex_structure(6)
1132     ) [ adopt(_3) ];
1134 This tells luabind to make Lua adopt the ownership and responsibility for the
1135 pointer passed in to the lua-function.
1137 It's important that all instances of object have been destructed by the time
1138 the Lua state is closed. The object will keep a pointer to the lua state and
1139 release its Lua object in its destructor.
1141 Here's an example of how a function can use a table::
1143     void my_function(object const& table)
1144     {
1145         if (type(table) == LUA_TTABLE)
1146         {
1147             table["time"] = std::clock();
1148             table["name"] = std::rand() < 500 ? "unusual" : "usual";
1150             std::cout << object_cast<std::string>(table[5]) << "\n";
1151         }
1152     }
1154 If you take a ``luabind::object`` as a parameter to a function, any Lua value
1155 will match that parameter. That's why we have to make sure it's a table before
1156 we index into it.
1159 Iterators
1160 ---------
1162 There are two kinds of iterators. The normal iterator that will use the metamethod
1163 of the object (if there is any) when the value is retrieved. This iterator is simply
1164 called ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator``
1165 and will bypass the metamethod and give the true contents of the table. They have
1166 identical interfaces, which implements the ForwardIterator_ concept. Apart from
1167 the members of standard iterators, they have the following members and constructors:
1169 .. _ForwardIterator: http://www.sgi.com/tech/stl/ForwardIterator.html
1171 .. parsed-literal::
1173     class iterator
1174     {
1175         iterator();
1176         iterator(object const&);
1178         object key() const;
1180         *standard iterator members*
1181     };
1183 The constructor that takes a ``luabind::object`` is actually a template that can be
1184 used with object. Passing an object as the parameter to the iterator will
1185 construct the iterator to refer to the first element in the object.
1187 The default constructor will initialize the iterator to the one-past-end
1188 iterator. This is used to test for the end of the sequence.
1190 The value type of the iterator is an implementation defined proxy type which
1191 supports the same operations as ``luabind::object``. Which means that in most
1192 cases you can just treat it as an ordinary object. The difference is that any
1193 assignments to this proxy will result in the value being inserted at the
1194 iterators position, in the table.
1196 The ``key()`` member returns the key used by the iterator when indexing the
1197 associated Lua table.
1199 An example using iterators::
1201     for (iterator i(globals(L)["a"]), end; i != end; ++i)
1202     {
1203       *i = 1;
1204     }
1206 The iterator named ``end`` will be constructed using the default constructor
1207 and hence refer to the end of the sequence. This example will simply iterate
1208 over the entries in the global table ``a`` and set all its values to 1.
1210 Related functions
1211 -----------------
1213 There are a couple of functions related to objects and tables.
1217     int type(object const&);
1219 This function will return the lua type index of the given object.
1220 i.e. ``LUA_TNIL``, ``LUA_TNUMBER`` etc.
1224     template<class T, class K>
1225     void settable(object const& o, K const& key, T const& value);
1226     template<class K>
1227     object gettable(object const& o, K const& key);
1228     template<class T, class K>
1229     void rawset(object const& o, K const& key, T const& value);
1230     template<class K>
1231     object rawget(object const& o, K const& key);
1233 These functions are used for indexing into tables. ``settable`` and ``gettable``
1234 translates into calls to ``lua_settable`` and ``lua_gettable`` respectively. Which
1235 means that you could just as well use the index operator of the object.
1237 ``rawset`` and ``rawget`` will translate into calls to ``lua_rawset`` and
1238 ``lua_rawget`` respectively. So they will bypass any metamethod and give you the
1239 true value of the table entry.
1243     template<class T>
1244     T object_cast<T>(object const&);
1245     template<class T, class Policies>
1246     T object_cast<T>(object const&, Policies);
1248     template<class T>
1249     boost::optional<T> object_cast_nothrow<T>(object const&);
1250     template<class T, class Policies>
1251     boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
1253 The ``object_cast`` function casts the value of an object to a C++ value.
1254 You can supply a policy to handle the conversion from lua to C++. If the cast
1255 cannot be made a ``cast_failed`` exception will be thrown. If you have
1256 defined LUABIND_NO_ERROR_CHECKING (see configuration) no checking will occur,
1257 and if the cast is invalid the application may very well crash. The nothrow
1258 versions will return an uninitialized ``boost::optional<T>`` object, to
1259 indicate that the cast could not be performed.
1261 The function signatures of all of the above functions are really templates
1262 for the object parameter, but the intention is that you should only pass
1263 objects in there, that's why it's left out of the documentation.
1267     object globals(lua_State*);
1268     object registry(lua_State*);
1270 These functions return the global environment table and the registry table respectively.
1274   object newtable(lua_State*);
1276 This function creates a new table and returns it as an object.
1279 Defining classes in Lua
1280 =======================
1282 In addition to binding C++ functions and classes with Lua, luabind also provide
1283 an OO-system in Lua. ::
1285     class 'lua_testclass'
1287     function lua_testclass:__init(name)
1288         self.name = name
1289     end
1291     function lua_testclass:print()
1292         print(self.name)
1293     end
1295     a = lua_testclass('example')
1296     a:print()
1299 Inheritance can be used between lua-classes::
1301     class 'derived' (lua_testclass)
1303     function derived:__init() super('derived name')
1304     end
1306     function derived:print()
1307         print('Derived:print() -> ')
1308         lua_testclass.print(self)
1309     end
1311 Here the ``super`` keyword is used in the constructor to initialize the base
1312 class. The user is required to call ``super`` first in the constructor.
1314 As you can see in this example, you can call the base class member functions.
1315 You can find all member functions in the base class, but you will have to give
1316 the this-pointer (``self``) as first argument.
1319 Deriving in lua
1320 ---------------
1322 It is also possible to derive Lua classes from C++ classes, and override
1323 virtual functions with Lua functions. To do this we have to create a wrapper
1324 class for our C++ base class. This is the class that will hold the Lua object
1325 when we instantiate a Lua class.
1329     class base
1330     {
1331     public:
1332         base(const char* s)
1333         { std::cout << s << "\n"; }
1335         virtual void f(int a) 
1336         { std::cout << "f(" << a << ")\n"; }
1337     };
1339     struct base_wrapper : base, luabind::wrap_base
1340     {
1341         base_wrapper(const char* s)
1342             : base(s) 
1343         {}
1345         virtual void f(int a) 
1346         { 
1347             call<void>("f", a); 
1348         }
1350         static void default_f(base* ptr, int a)
1351         {
1352             return ptr->base::f(a);
1353         }
1354     };
1356     ...
1358     module(L)
1359     [
1360         class_<base, base_wrapper>("base")
1361             .def(constructor<const char*>())
1362             .def("f", &base::f, &base_wrapper::default_f)
1363     ];
1365 .. Important::
1366     Since MSVC6.5 doesn't support explicit template parameters
1367     to member functions, instead of using the member function ``call()``
1368     you call a free function ``call_member()`` and pass the this-pointer
1369     as first parameter.
1371 Note that if you have both base classes and a base class wrapper, you must give
1372 both bases and the base class wrapper type as template parameter to 
1373 ``class_`` (as done in the example above). The order in which you specify
1374 them is not important. You must also register both the static version and the
1375 virtual version of the function from the wrapper, this is necessary in order
1376 to allow luabind to use both dynamic and static dispatch when calling the function.
1378 .. Important::
1379     It is extremely important that the signatures of the static (default) function
1380     is identical to the virtual function. The fact that one of them is a free
1381     function and the other a member function doesn't matter, but the parameters
1382     as seen from lua must match. It would not have worked if the static function
1383     took a ``base_wrapper*`` as its first argument, since the virtual function
1384     takes a ``base*`` as its first argument (its this pointer). There's currently
1385     no check in luabind to make sure the signatures match.
1387 If we didn't have a class wrapper, it would not be possible to pass a Lua class
1388 back to C++. Since the entry points of the virtual functions would still point
1389 to the C++ base class, and not to the functions defined in Lua. That's why we
1390 need one function that calls the base class' real function (used if the lua
1391 class doesn't redefine it) and one virtual function that dispatches the call
1392 into luabind, to allow it to select if a Lua function should be called, or if
1393 the original function should be called. If you don't intend to derive from a
1394 C++ class, or if it doesn't have any virtual member functions, you can register
1395 it without a class wrapper.
1397 You don't need to have a class wrapper in order to derive from a class, but if
1398 it has virtual functions you may have silent errors. 
1400 .. Unnecessary? The rule of thumb is: 
1401   If your class has virtual functions, create a wrapper type, if it doesn't
1402   don't create a wrapper type.
1404 The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference
1405 that will hold the Lua instance of the object to make it possible to dispatch
1406 virtual function calls into Lua. This is done through an overloaded member function::
1408     template<class Ret>
1409     Ret call(char const* name, ...)
1411 Its used in a similar way as ``call_function``, with the exception that it doesn't
1412 take a ``lua_State`` pointer, and the name is a member function in the Lua class.
1414 .. warning::
1416         The current implementation of ``call_member`` is not able to distinguish const
1417         member functions from non-const. If you have a situation where you have an overloaded
1418         virtual function where the only difference in their signatures is their constness, the
1419         wrong overload will be called by ``call_member``. This is rarely the case though.
1421 Object identity
1422 ~~~~~~~~~~~~~~~
1424 When a pointer or reference to a registered class with a wrapper is passed
1425 to Lua, luabind will query for it's dynamic type. If the dynamic type
1426 inherits from ``wrap_base``, object identity is preserved.
1430     struct A { .. };
1431     struct A_wrap : A, wrap_base { .. };
1433     A* f(A* ptr) { return ptr; }
1435     module(L)
1436     [
1437         class_<A, A_wrap>("A"),
1438         def("f", &f)
1439     ];
1443     > class 'B' (A)
1444     > x = B()
1445     > assert(x == f(x)) -- object identity is preserved when object is
1446                         -- passed through C++
1448 This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is
1449 not defined).
1451 Overloading operators
1452 ---------------------
1454 You can overload most operators in Lua for your classes. You do this by simply
1455 declaring a member function with the same name as an operator (the name of the
1456 metamethods in Lua). The operators you can overload are:
1458  - ``__add``
1459  - ``__sub`` 
1460  - ``__mul`` 
1461  - ``__div`` 
1462  - ``__pow`` 
1463  - ``__lt`` 
1464  - ``__le`` 
1465  - ``__eq`` 
1466  - ``__call`` 
1467  - ``__unm`` 
1468  - ``__tostring``
1470 ``__tostring`` isn't really an operator, but it's the metamethod that is called
1471 by the standard library's ``tostring()`` function. There's one strange behavior
1472 regarding binary operators. You are not guaranteed that the self pointer you
1473 get actually refers to an instance of your class. This is because Lua doesn't
1474 distinguish the two cases where you get the other operand as left hand value or
1475 right hand value. Consider the following examples::
1477     class 'my_class'
1479       function my_class:__init(v)
1480           self.val = v
1481       end
1482         
1483       function my_class:__sub(v)
1484           return my_class(self.val - v.val)
1485       end
1487       function my_class:__tostring()
1488           return self.val
1489       end
1491 This will work well as long as you only subtracts instances of my_class with
1492 each other. But If you want to be able to subtract ordinary numbers from your
1493 class too, you have to manually check the type of both operands, including the
1494 self object. ::
1496     function my_class:__sub(v)
1497         if (type(self) == 'number') then
1498             return my_class(self - v.val)
1500         elseif (type(v) == 'number') then
1501             return my_class(self.val - v)
1502         
1503         else
1504             -- assume both operands are instances of my_class
1505             return my_class(self.val - v.val)
1507         end
1508     end
1510 The reason why ``__sub`` is used as an example is because subtraction is not
1511 commutative (the order of the operands matter). That's why luabind cannot
1512 change order of the operands to make the self reference always refer to the
1513 actual class instance.
1515 If you have two different Lua classes with an overloaded operator, the operator
1516 of the right hand side type will be called. If the other operand is a C++ class
1517 with the same operator overloaded, it will be prioritized over the Lua class'
1518 operator. If none of the C++ overloads matches, the Lua class operator will be
1519 called.
1522 Finalizers
1523 ----------
1525 If an object needs to perform actions when it's collected we provide a
1526 ``__finalize`` function that can be overridden in lua-classes. The
1527 ``__finalize`` functions will be called on all classes in the inheritance
1528 chain, starting with the most derived type. ::
1530     ...
1532     function lua_testclass:__finalize()
1533         -- called when the an object is collected
1534     end
1537 Slicing
1538 -------
1540 If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and
1541 you derive from them in lua, they may be sliced. Meaning, if an object
1542 is passed into C++ as a pointer to its base class, the lua part will be
1543 separated from the C++ base part. This means that if you call virtual
1544 functions on that C++ object, they will not be dispatched to the lua
1545 class. It also means that if you adopt the object, the lua part will be
1546 garbage collected.
1550         +--------------------+
1551         | C++ object         |    <- ownership of this part is transferred
1552         |                    |       to c++ when adopted
1553         +--------------------+
1554         | lua class instance |    <- this part is garbage collected when
1555         | and lua members    |       instance is adopted, since it cannot
1556         +--------------------+       be held by c++. 
1559 The problem can be illustrated by this example::
1561     struct A {};
1563     A* filter_a(A* a) { return a; }
1564     void adopt_a(A* a) { delete a; }
1569     using namespace luabind;
1571     module(L)
1572     [
1573         class_<A>("A"),
1574         def("filter_a", &filter_a),
1575         def("adopt_a", &adopt_a, adopt(_1))
1576     ]
1579 In lua::
1581     a = A()
1582     b = filter_a(a)
1583     adopt_a(b)
1585 In this example, lua cannot know that ``b`` actually is the same object as
1586 ``a``, and it will therefore consider the object to be owned by the C++ side.
1587 When the ``b`` pointer then is adopted, a runtime error will be raised because
1588 an object not owned by lua is being adopted to C++.
1590 If you have a wrapper for your class, none of this will happen, see
1591 `Object identity`_.
1594 Exceptions
1595 ==========
1597 If any of the functions you register throws an exception when called, that
1598 exception will be caught by luabind and converted to an error string and
1599 ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
1600 ``const char*`` the string that is pushed on the Lua stack, as error message,
1601 will be the string returned by ``std::exception::what()`` or the string itself
1602 respectively. If the exception is unknown, a generic string saying that the
1603 function threw an exception will be pushed.
1605 Exceptions thrown from user defined functions have to be caught by luabind. If
1606 they weren't they would be thrown through Lua itself, which is usually compiled
1607 as C code and doesn't support the stack-unwinding that exceptions imply.
1609 Any function that invokes Lua code may throw ``luabind::error``. This exception
1610 means that a Lua run-time error occurred. The error message is found on top of
1611 the Lua stack. The reason why the exception doesn't contain the error string
1612 itself is because it would then require heap allocation which may fail. If an
1613 exception class throws an exception while it is being thrown itself, the
1614 application will be terminated.
1616 Error's synopsis is::
1618     class error : public std::exception
1619     {
1620     public:
1621         error(lua_State*);
1622         lua_State* state() const throw();
1623         virtual const char* what() const throw();
1624     };
1626 The state function returns a pointer to the Lua state in which the error was
1627 thrown. This pointer may be invalid if you catch this exception after the lua
1628 state is destructed. If the Lua state is valid you can use it to retrieve the
1629 error message from the top of the Lua stack.
1631 An example of where the Lua state pointer may point to an invalid state
1632 follows::
1634     struct lua_state
1635     {
1636         lua_state(lua_State* L): m_L(L) {}
1637         ~lua_state() { lua_close(m_L); }
1638         operator lua_State*() { return m_L; }
1639         lua_State* m_L;
1640     };
1642     int main()
1643     {
1644         try
1645         {
1646             lua_state L = lua_open();
1647             /* ... */
1648         }
1649         catch(luabind::error& e)
1650         {
1651             lua_State* L = e.state();
1652             // L will now point to the destructed
1653             // Lua state and be invalid
1654             /* ... */
1655         }
1656     }
1658 There's another exception that luabind may throw: ``luabind::cast_failed``,
1659 this exception is thrown from ``call_function<>`` or ``call_member<>``. It
1660 means that the return value from the Lua function couldn't be converted to
1661 a C++ value. It is also thrown from ``object_cast<>`` if the cast cannot
1662 be made.
1664 The synopsis for ``luabind::cast_failed`` is::
1666     class cast_failed : public std::exception
1667     {
1668     public:
1669         cast_failed(lua_State*);
1670         lua_State* state() const throw();
1671         LUABIND_TYPE_INFO info() const throw();
1672         virtual const char* what() const throw();
1673     };
1675 Again, the state member function returns a pointer to the Lua state where the
1676 error occurred. See the example above to see where this pointer may be invalid.
1678 The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
1679 defaults to a ``const std::type_info*``. This type info describes the type that
1680 we tried to cast a Lua value to.
1682 If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
1683 thrown, instead you can set two callback functions that are called instead.
1684 These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
1688     luabind::set_error_callback(void(*)(lua_State*))
1690 The function you set will be called when a runtime-error occur in Lua code. You
1691 can find an error message on top of the Lua stack. This function is not
1692 expected to return, if it does luabind will call ``std::terminate()``.
1696     luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1698 The function you set is called instead of throwing ``cast_failed``. This function
1699 is not expected to return, if it does luabind will call ``std::terminate()``.
1702 Policies
1703 ========
1705 Sometimes it is necessary to control how luabind passes arguments and return
1706 value, to do this we have policies. All policies use an index to associate
1707 them with an argument in the function signature. These indices are ``result`` 
1708 and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers
1709 to the ``this`` pointer.
1711 .. contents:: Policies currently implemented
1712     :local:
1713     :depth: 1
1715 .. include:: adopt.rst
1716 .. include:: dependency.rst
1717 .. include:: out_value.rst
1718 .. include:: pure_out_value.rst
1719 .. include:: return_reference_to.rst
1720 .. include:: copy.rst
1721 .. include:: discard_result.rst
1722 .. include:: return_stl_iterator.rst
1723 .. include:: raw.rst
1724 .. include:: yield.rst
1726 ..  old policies section
1727     ===================================================
1729     Copy
1730     ----
1732     This will make a copy of the parameter. This is the default behavior when
1733     passing parameters by-value. Note that this can only be used when passing from
1734     C++ to Lua. This policy requires that the parameter type has a copy
1735     constructor.
1737     To use this policy you need to include ``luabind/copy_policy.hpp``.
1740     Adopt
1741     -----
1743     This will transfer ownership of the parameter.
1745     Consider making a factory function in C++ and exposing it to lua::
1747         base* create_base()
1748         {
1749             return new base();
1750         }
1752         ...
1754         module(L)
1755         [
1756             def("create_base", create_base)
1757         ];
1759     Here we need to make sure Lua understands that it should adopt the pointer
1760     returned by the factory-function. This can be done using the adopt-policy.
1762     ::
1764         module(L)
1765         [
1766             def(L, "create_base", adopt(return_value))
1767         ];
1769     To specify multiple policies we just separate them with '+'.
1771     ::
1773         base* set_and_get_new(base* ptr)
1774         {
1775             base_ptrs.push_back(ptr);
1776             return new base();
1777         }
1779         module(L)
1780         [
1781             def("set_and_get_new", &set_and_get_new, 
1782                 adopt(return_value) + adopt(_1))
1783         ];
1785     When Lua adopts a pointer, it will call delete on it. This means that it cannot
1786     adopt pointers allocated with another allocator than new (no malloc for
1787     example).
1789     To use this policy you need to include ``luabind/adopt_policy.hpp``.
1792     Dependency
1793     ----------
1795     The dependency policy is used to create life-time dependencies between values.
1796     Consider the following example::
1798         struct A
1799         {
1800             B member;
1802             const B& get_member()
1803             {
1804                 return member;
1805             }
1806         };
1808     When wrapping this class, we would do something like::
1810         module(L)
1811         [
1812             class_<A>("A")
1813                 .def(constructor<>())
1814                 .def("get_member", &A::get_member)
1815         ];
1818     However, since the return value of get_member is a reference to a member of A,
1819     this will create some life-time issues. For example::
1821         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1822         a = A()
1823         b = a:get_member() -- b points to a member of a
1824         a = nil
1825         collectgarbage(0)  -- since there are no references left to a, it is
1826                            -- removed
1827                            -- at this point, b is pointing into a removed object
1829     When using the dependency-policy, it is possible to tell luabind to tie the
1830     lifetime of one object to another, like this::
1832         module(L)
1833         [
1834             class_<A>("A")
1835                 .def(constructor<>())
1836                 .def("get_member", &A::get_member, dependency(result, _1))
1837         ];
1839     This will create a dependency between the return-value of the function, and the
1840     self-object. This means that the self-object will be kept alive as long as the
1841     result is still alive. ::
1843         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1844         a = A()
1845         b = a:get_member() -- b points to a member of a
1846         a = nil
1847         collectgarbage(0)  -- a is dependent on b, so it isn't removed
1848         b = nil
1849         collectgarbage(0)  -- all dependencies to a gone, a is removed
1851     To use this policy you need to include ``luabind/dependency_policy.hpp``.
1854     Return reference to
1855     -------------------
1857     It is very common to return references to arguments or the this-pointer to
1858     allow for chaining in C++.
1860     ::
1862         struct A
1863         {
1864             float val;
1866             A& set(float v)
1867             {
1868                 val = v;
1869                 return *this;
1870             }
1871         };
1873     When luabind generates code for this, it will create a new object for the
1874     return-value, pointing to the self-object. This isn't a problem, but could be a
1875     bit inefficient. When using the return_reference_to-policy we have the ability
1876     to tell luabind that the return-value is already on the Lua stack.
1878     ::
1880         module(L)
1881         [
1882             class_<A>("A")
1883                 .def(constructor<>())
1884                 .def("set", &A::set, return_reference_to(_1))
1885         ];
1887     Instead of creating a new object, luabind will just copy the object that is
1888     already on the stack.
1890     .. warning:: 
1891        This policy ignores all type information and should be used only it 
1892        situations where the parameter type is a perfect match to the 
1893        return-type (such as in the example).
1895     To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
1898     Out value
1899     ---------
1901     This policy makes it possible to wrap functions that take non const references
1902     as its parameters with the intention to write return values to them.
1904     ::
1906         void f(float& val) { val = val + 10.f; }
1908     or
1910     ::
1912         void f(float* val) { *val = *val + 10.f; }
1914     Can be wrapped by doing::
1916         module(L)
1917         [
1918             def("f", &f, out_value(_1))
1919         ];
1921     When invoking this function from Lua it will return the value assigned to its 
1922     parameter.
1924     ::
1926         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1927         > a = f(10)
1928         > print(a)
1929         20
1931     When this policy is used in conjunction with user define types we often need 
1932     to do ownership transfers.
1934     ::
1936         struct A;
1938         void f1(A*& obj) { obj = new A(); }
1939         void f2(A** obj) { *obj = new A(); }
1941     Here we need to make sure luabind takes control over object returned, for 
1942     this we use the adopt policy::
1944         module(L)
1945         [
1946             class_<A>("A"),
1947             def("f1", &f1, out_value(_1, adopt(_2)))
1948             def("f2", &f2, out_value(_1, adopt(_2)))
1949         ];
1951     Here we are using adopt as an internal policy to out_value. The index 
1952     specified, _2, means adopt will be used to convert the value back to Lua. 
1953     Using _1 means the policy will be used when converting from Lua to C++.
1955     To use this policy you need to include ``luabind/out_value_policy.hpp``.
1957     Pure out value
1958     --------------
1960     This policy works in exactly the same way as out_value, except that it 
1961     replaces the parameters with default-constructed objects.
1963     ::
1965         void get(float& x, float& y)
1966         {
1967             x = 3.f;
1968             y = 4.f;
1969         }
1971         ...
1973         module(L)
1974         [
1975             def("get", &get, 
1976                 pure_out_value(_1) + pure_out_value(_2))
1977         ];
1979     ::
1981         Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1982         > x, y = get()
1983         > print(x, y)
1984         3    5
1986     Like out_value, it is possible to specify an internal policy used then 
1987     converting the values back to Lua.
1989     ::
1991         void get(test_class*& obj)
1992         {
1993             obj = new test_class();
1994         }
1996         ...
1998         module(L)
1999         [
2000             def("get", &get, pure_out_value(_1, adopt(_1)))
2001         ];
2004     Discard result
2005     --------------
2007     This is a very simple policy which makes it possible to throw away 
2008     the value returned by a C++ function, instead of converting it to 
2009     Lua. This example makes sure the this reference never gets converted 
2010     to Lua.
2012     ::
2014         struct simple
2015         {
2016             simple& set_name(const std::string& n)
2017             {
2018                 name = n;
2019                 return *this;
2020             }
2022             std::string name;
2023         };
2025         ...
2027         module(L)
2028         [
2029             class_<simple>("simple")
2030                 .def("set_name", &simple::set_name, discard_result)
2031         ];
2033     To use this policy you need to include ``luabind/discard_result_policy.hpp``.
2036     Return STL iterator
2037     -------------------
2039     This policy converts an STL container to a generator function that can be used
2040     in Lua to iterate over the container. It works on any container that defines
2041     ``begin()`` and ``end()`` member functions (they have to return iterators). It
2042     can be used like this::
2044         struct A
2045         {
2046             std::vector<std::string> names;
2047         };
2050         module(L)
2051         [
2052             class_<A>("A")
2053                 .def_readwrite("names", &A::names, return_stl_iterator)
2054         ];
2056     The Lua code to iterate over the container::
2058         a = A()
2060         for name in a.names do
2061           print(name)
2062         end
2065     To use this policy you need to include ``luabind/iterator_policy.hpp``.
2068     Yield
2069     -----    
2071     This policy will cause the function to always yield the current thread when 
2072     returning. See the Lua manual for restrictions on yield.
2075 Splitting up the registration
2076 =============================
2078 It is possible to split up a module registration into several
2079 translation units without making each registration dependent
2080 on the module it's being registered in.
2082 ``a.cpp``::
2084     luabind::scope register_a()
2085     {
2086         return 
2087             class_<a>("a")
2088                 .def("f", &a::f)
2089                 ;
2090     }
2092 ``b.cpp``::
2094     luabind::scope register_b()
2095     {
2096         return 
2097             class_<b>("b")
2098                 .def("g", &b::g)
2099                 ;
2100     }
2102 ``module_ab.cpp``::
2104     luabind::scope register_a();
2105     luabind::scope register_b();
2107     void register_module(lua_State* L)
2108     {
2109         module("b", L)
2110         [
2111             register_a(),
2112             register_b()
2113         ];
2114     }
2117 Configuration
2118 =============
2120 As mentioned in the `Lua documentation`_, it is possible to pass an
2121 error handler function to ``lua_pcall()``. Luabind makes use of 
2122 ``lua_pcall()`` internally when calling member functions and free functions.
2123 It is possible to set the error handler function that Luabind will use
2124 globally::
2126     typedef void(*pcall_callback_fun)(lua_State*);
2127     void set_pcall_callback(pcall_callback_fun fn);
2129 This is primarily useful for adding more information to the error message
2130 returned by a failed protected call.
2132 .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
2134 Build options
2135 -------------
2137 There are a number of configuration options available when building luabind.
2138 It is very important that your project has the exact same configuration 
2139 options as the ones given when the library was build! The exceptions are the
2140 ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based 
2141 options and only matters when you use the library (which means they can 
2142 differ from the settings of the library).
2144 The default settings which will be used if no other settings are given
2145 can be found in ``luabind/config.hpp``.
2147 If you want to change the settings of the library, you can modify the 
2148 config file. It is included and used by all makefiles. You can change paths
2149 to Lua and boost in there as well.
2151 LUABIND_MAX_ARITY
2152     Controls the maximum arity of functions that are registered with luabind. 
2153     You can't register functions that takes more parameters than the number 
2154     this macro is set to. It defaults to 5, so, if your functions have greater 
2155     arity you have to redefine it. A high limit will increase compilation time.
2157 LUABIND_MAX_BASES
2158     Controls the maximum number of classes one class can derive from in 
2159     luabind (the number of classes specified within ``bases<>``). 
2160     ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase 
2161     compilation time.
2163 LUABIND_NO_ERROR_CHECKING
2164     If this macro is defined, all the Lua code is expected only to make legal 
2165     calls. If illegal function calls are made (e.g. giving parameters that 
2166     doesn't match the function signature) they will not be detected by luabind
2167     and the application will probably crash. Error checking could be disabled 
2168     when shipping a release build (given that no end-user has access to write 
2169     custom Lua code). Note that function parameter matching will be done if a 
2170     function is overloaded, since otherwise it's impossible to know which one 
2171     was called. Functions will still be able to throw exceptions when error 
2172     checking is disabled.
2174     If a function throws an exception it will be caught by luabind and 
2175     propagated with ``lua_error()``.
2177 LUABIND_NO_EXCEPTIONS
2178     This define will disable all usage of try, catch and throw in luabind. 
2179     This will in many cases disable run-time errors, when performing invalid 
2180     casts or calling Lua functions that fails or returns values that cannot 
2181     be converted by the given policy. luabind requires that no function called 
2182     directly or indirectly by luabind throws an exception (throwing exceptions 
2183     through Lua has undefined behavior).
2185     Where exceptions are the only way to get an error report from luabind, 
2186     they will be replaced with calls to the callback functions set with
2187     ``set_error_callback()`` and ``set_cast_failed_callback()``.
2189 LUA_API
2190     If you want to link dynamically against Lua, you can set this define to 
2191     the import-keyword on your compiler and platform. On windows in devstudio 
2192     this should be ``__declspec(dllimport)`` if you want to link against Lua 
2193     as a dll.
2195 LUABIND_EXPORT, LUABIND_IMPORT
2196     If you want to link against luabind as a dll (in devstudio), you can 
2197     define ``LUABIND_EXPORT`` to ``__declspec(dllexport)`` and 
2198     ``LUABIND_IMPORT`` to ``__declspec(dllimport)`` or
2199     ``__attribute__ ((visibility("default")))`` on GCC 4. 
2200     Note that you have to link against Lua as a dll aswell, to make it work.
2202 LUABIND_NO_RTTI
2203     You can define this if you don't want luabind to use ``dynamic_cast<>``.
2204     It will disable `Object identity`_.
2206 LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO
2207     If you don't want to use the RTTI supplied by C++ you can supply your own 
2208     type-info structure with the ``LUABIND_TYPE_INFO`` define. Your type-info 
2209     structure must be copyable and must be able to compare itself against 
2210     other type-info structures. You supply the compare function through the 
2211     ``LUABIND_TYPE_INFO_EQUAL()`` define. It should compare the two type-info 
2212     structures it is given and return true if they represent the same type and
2213     false otherwise. You also have to supply a function to generate your 
2214     type-info structure. You do this through the ``LUABIND_TYPEID()`` define. 
2215     It should return your type-info structure and it takes a type as its 
2216     parameter. That is, a compile time parameter. 
2217     ``LUABIND_INVALID_TYPE_INFO`` macro should be defined to an invalid type. 
2218     No other type should be able to produce this type info. To use it you 
2219     probably have to make a traits class with specializations for all classes 
2220     that you have type-info for. Like this::
2222         class A;
2223         class B;
2224         class C;
2226         template<class T> struct typeinfo_trait;
2228         template<> struct typeinfo_trait<A> { enum { type_id = 0 }; };
2229         template<> struct typeinfo_trait<B> { enum { type_id = 1 }; };
2230         template<> struct typeinfo_trait<C> { enum { type_id = 2 }; };
2232     If you have set up your own RTTI system like this (by using integers to
2233     identify types) you can have luabind use it with the following defines::
2235         #define LUABIND_TYPE_INFO const std::type_info*
2236         #define LUABIND_TYPEID(t) &typeid(t)
2237         #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
2238         #define LUABIND_INVALID_TYPE_INFO &typeid(detail::null_type)
2240     Currently the type given through ``LUABIND_TYPE_INFO`` must be less-than 
2241     comparable!
2243 NDEBUG
2244     This define will disable all asserts and should be defined in a release 
2245     build.
2248 Implementation notes
2249 ====================
2251 The classes and objects are implemented as user data in Lua. To make sure that
2252 the user data really is the internal structure it is supposed to be, we tag
2253 their metatables. A user data who's metatable contains a boolean member named
2254 ``__luabind_classrep`` is expected to be a class exported by luabind. A user
2255 data who's metatable contains a boolean member named ``__luabind_class`` is
2256 expected to be an instantiation of a luabind class.
2258 This means that if you make your own user data and tags its metatable with the
2259 exact same names, you can very easily fool luabind and crash the application.
2261 In the Lua registry, luabind keeps an entry called ``__luabind_classes``. It
2262 should not be removed or overwritten.
2264 In the global table, a variable called ``super`` is used every time a
2265 constructor in a lua-class is called. This is to make it easy for that
2266 constructor to call its base class' constructor. So, if you have a global
2267 variable named super it may be overwritten. This is probably not the best
2268 solution, and this restriction may be removed in the future.
2270 Luabind uses two upvalues for functions that it registers. The first is a
2271 userdata containing a list of overloads for the function, the other is a light
2272 userdata with the value 0x1337, this last value is used to identify functions
2273 registered by luabind. It should be virtually impossible to have such a pointer
2274 as secondary upvalue by pure chance. This means, if you are trying to replace
2275 an existing function with a luabind function, luabind will see that the
2276 secondary upvalue isn't the magic id number and replace it. If it can identify
2277 the function to be a luabind function, it won't replace it, but rather add
2278 another overload to it.
2280 Inside the luabind namespace, there's another namespace called detail. This
2281 namespace contains non-public classes and are not supposed to be used directly.
2284 Error messages
2285 ==============
2287 - .. parsed-literal::
2289     the attribute '*class-name.attribute-name*' is read only
2291   There is no data member named *attribute-name* in the class *class-name*,
2292   or there's no setter-function registered on that property name. See the 
2293   Properties_ section.
2295 - .. parsed-literal:: 
2297     the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*)
2299   This error is generated if you try to assign an attribute with a value 
2300   of a type that cannot be converted to the attribute's type.
2303 - .. parsed-literal:: 
2305     *class-name()* threw an exception, *class-name:function-name()* threw an exception
2307   The class' constructor or member function threw an unknown exception.
2308   Known exceptions are const char*, std::exception. See the 
2309   `exceptions`_ section.
2311 - .. parsed-literal::
2313     no overload of '*class-name:function-name*' matched the arguments (*parameter-types*)
2314     no match for function call '*function-name*' with the parameters (*parameter-types*)
2315     no constructor of *class-name* matched the arguments (*parameter-types*)
2316     no operator *operator-name* matched the arguments (*parameter-types*)
2318   No function/operator with the given name takes the parameters you gave 
2319   it. You have either misspelled the function name, or given it incorrect
2320   parameters. This error is followed by a list of possible candidate 
2321   functions to help you figure out what parameter has the wrong type. If
2322   the candidate list is empty there's no function at all with that name.
2323   See the signature matching section.
2325 - .. parsed-literal::
2327     call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous
2328     ambiguous match for function call '*function-name*' with the parameters (*parameter-types*)
2329     call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous
2330     call of overloaded operator *operator-name* (*parameter-types*) is ambiguous
2332   This means that the function/operator you are trying to call has at least
2333   one other overload that matches the arguments just as good as the first
2334   overload.
2336 - .. parsed-literal::
2338     cannot derive from C++ class '*class-name*'. It does not have a wrapped type.
2344 What's up with __cdecl and __stdcall?
2345     If you're having problem with functions
2346     that cannot be converted from ``void (__stdcall *)(int,int)`` to 
2347     ``void (__cdecl*)(int,int)``. You can change the project settings to make the
2348     compiler generate functions with __cdecl calling conventions. This is
2349     a problem in developer studio.
2351 What's wrong with functions taking variable number of arguments?
2352     You cannot register a function with ellipses in its signature. Since
2353     ellipses don't preserve type safety, those should be avoided anyway.
2355 Internal structure overflow in VC
2356     If you, in visual studio, get fatal error C1204: compiler limit :
2357     internal structure overflow. You should try to split that compilation
2358     unit up in smaller ones. See `Splitting up the registration`_ and
2359     `Splitting class registrations`_.
2361 .. the three entries above were removed, why?
2363 What's wrong with precompiled headers in VC?
2364     Visual Studio doesn't like anonymous namespace's in its precompiled 
2365     headers. If you encounter this problem you can disable precompiled 
2366     headers for the compilation unit (cpp-file) that uses luabind.
2368 error C1076: compiler limit - internal heap limit reached in VC
2369     In visual studio you will probably hit this error. To fix it you have to
2370     increase the internal heap with a command-line option. We managed to
2371     compile the test suit with /Zm300, but you may need a larger heap then 
2372     that.
2374 error C1055: compiler limit \: out of keys in VC
2375     It seems that this error occurs when too many assert() are used in a
2376     program, or more specifically, the __LINE__ macro. It seems to be fixed by
2377     changing /ZI (Program database for edit and continue) to /Zi 
2378     (Program database).
2380 How come my executable is huge?
2381     If you're compiling in debug mode, you will probably have a lot of
2382     debug-info and symbols (luabind consists of a lot of functions). Also, 
2383     if built in debug mode, no optimizations were applied, luabind relies on 
2384     that the compiler is able to inline functions. If you built in release 
2385     mode, try running strip on your executable to remove export-symbols, 
2386     this will trim down the size.
2388     Our tests suggests that cygwin's gcc produces much bigger executables 
2389     compared to gcc on other platforms and other compilers.
2391 .. HUH?! // check the magic number that identifies luabind's functions 
2393 Can I register class templates with luabind?
2394     Yes you can, but you can only register explicit instantiations of the 
2395     class. Because there's no Lua counterpart to C++ templates. For example, 
2396     you can register an explicit instantiation of std::vector<> like this::
2398         module(L)
2399         [
2400             class_<std::vector<int> >("vector")
2401                 .def(constructor<int>)
2402                 .def("push_back", &std::vector<int>::push_back)
2403         ];
2405 .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
2407 Do I have to register destructors for my classes?
2408     No, the destructor of a class is always called by luabind when an 
2409     object is collected. Note that Lua has to own the object to collect it.
2410     If you pass it to C++ and gives up ownership (with adopt policy) it will 
2411     no longer be owned by Lua, and not collected.
2413     If you have a class hierarchy, you should make the destructor virtual if 
2414     you want to be sure that the correct destructor is called (this apply to C++ 
2415     in general).
2417 .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ. But it saves us support questions.
2419 Fatal Error C1063 compiler limit \: compiler stack overflow in VC
2420     VC6.5 chokes on warnings, if you are getting alot of warnings from your 
2421     code try suppressing them with a pragma directive, this should solve the 
2422     problem.
2424 Crashes when linking against luabind as a dll in windows
2425     When you build luabind, Lua and you project, make sure you link against 
2426     the runtime dynamically (as a dll).
2428 I cannot register a function with a non-const parameter
2429     This is because there is no way to get a reference to a Lua value. Have 
2430     a look at out_value_ and pure_out_value_ policies.
2433 Known issues
2434 ============
2436 - You cannot use strings with extra nulls in them as member names that refers
2437   to C++ members.
2439 - If one class registers two functions with the same name and the same
2440   signature, there's currently no error. The last registered function will
2441   be the one that's used.
2443 - In VC7, classes can not be called test.
2445 - If you register a function and later rename it, error messages will use the
2446   original function name.
2448 - luabind does not support class hierarchies with virtual inheritance. Casts are
2449   done with static pointer offsets.
2451 .. remove? - Visual studio have problems selecting the correct overload of std::swap()
2452   for luabind::object.
2455 Acknowledgments
2456 ===============
2458 Written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
2459 All rights reserved.
2461 Evan Wies has contributed with thorough testing, countless bug reports
2462 and feature ideas.
2464 This library was highly inspired by Dave Abrahams' Boost.Python_ library.
2466 .. _Boost.Python: http://www.boost.org/libraries/python