5 :Author: Daniel Wallin, Arvid Norberg
6 :Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.
9 :License: Permission is hereby granted, free of charge, to any person obtaining a
10 copy of this software and associated documentation files (the "Software"),
11 to deal in the Software without restriction, including without limitation
12 the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 and/or sell copies of the Software, and to permit persons to whom the
14 Software is furnished to do so, subject to the following conditions:
16 The above copyright notice and this permission notice shall be included
17 in all copies or substantial portions of the Software.
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20 ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23 SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
24 ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
27 OR OTHER DEALINGS IN THE SOFTWARE.
30 .. _MIT license: http://www.opensource.org/licenses/mit-license.php
31 .. _Boost: http://www.boost.org
33 Note: This library is currently in public beta phase. This documentation
34 should be considered beta as well. Please report any grammatical
35 corrections/spelling corrections.
39 .. section-numbering::
44 Luabind is a library that helps you create bindings between C++ and Lua. It has
45 the ability to expose functions and classes, written in C++, to Lua. It will
46 also supply the functionality to define classes in Lua and let them derive from
47 other Lua classes or C++ classes. Lua classes can override virtual functions
48 from their C++ base classes. It is written towards Lua 5.0, and does not work
51 It is implemented utilizing template meta programming. That means that you
52 don't need an extra preprocess pass to compile your project (it is done by the
53 compiler). It also means you don't (usually) have to know the exact signatureof
54 each function you register, since the library will generate code depending on
55 the compile-time type of the function (which includes the signature). The main
56 drawback of this approach is that the compilation time will increase for the
57 file that does the registration, it is therefore recommended that you register
58 everything in the same cpp-file.
60 luabind is released under the terms of the `MIT license`_.
62 We are very interested in hearing about projects that use luabind, please let
63 us know about your project.
71 - Overloaded free functions
73 - Overloaded member functions
77 - Lua functions in C++
79 - Lua classes (single inheritance)
80 - Derives from Lua or C++ classes
81 - Override virtual functions from C++ classes
82 - Implicit casts between registered types
83 - Best match signature matching
84 - Return value policies and parameter policies
90 Luabind has been tested to work on the following compilers:
94 - Visual Studio 6.0 (sp 5)
95 - Intel C++ 6.0 (Windows)
97 - GCC 3.0.4 (Debian/Linux)
102 It has been confirmed not to work with:
104 - GCC 2.95.2 (SunOS 5.8)
106 Metrowerks 8.3 (Windows) compiles but fails the const-test. This
107 means that const member functions are treated as non-const member
110 If you have tried luabind with a compiler not listed here, let us know
117 To keep down the compilation-time luabind is built as a library. This means you
118 have to either build it and lika against it, or include its source files in
119 your project. You also have to make sure the luabind directory is somewhere in
120 your compiler's include path. It requires `Boost`_ 1.31.0 to be installed (only
121 boost headers). It also requires that Lua is installed.
123 The official way of building luabind is with `Boost.Build V2`_. To properly build
124 luabind with Boost.Build you need to set two environment variables:
127 Point this to your Boost installation.
130 Point this to your Lua directory. The build system will assume that the
131 include and library files are located in ``$(LUA_PATH)/include/`` and
132 ``$(LUA_PATH)/lib/.``
134 For backward compatibility, there is also a makefile in the root-directory that
135 will build the library and the test program. If you are using a UNIX-system (or
136 cygwin) they will make it easy to build luabind as a static library. If you are
137 using Visual Studio it may be easier to include the files in the src directory
140 When building luabind you have several options that may streamline the library
141 to better suit your needs. It is extremely important that your application has
142 the same settings as the library was built with. The available options are
143 found in the `Configuration`_ section.
145 If you want to change the settings to differ from the default, it's recommended
146 that you define the settings on the commandline of all your files (in the
147 project settings in visual studio).
149 .. _`Boost.Build V2`: http://www.boost.org/tools/build/v2/index_v2.html
155 To use luabind, you must include ``lua.h`` and luabind's main header file::
162 #include <luabind/luabind.hpp>
164 This includes support for both registering classes and functions. If you just
165 want to have support for functions or classes you can include
166 ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
168 #include <luabind/function.hpp>
169 #include <luabind/class.hpp>
171 The first thing you need to do is to call ``luabind::open(lua_State*)`` which
172 will register the functions to create classes from Lua, and initialize some
173 state-global structures used by luabind. If you don't call this function you
174 will hit asserts later in the library. There is no corresponding close function
175 because once a class has been registered in Lua, there really isn't any good
176 way to remove it. Partly because any remaining instances of that class relies
177 on the class being there. Everything will be cleaned up when the state is
180 .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
182 Luabind's headers will never include ``lua.h`` directly, but through
183 ``<luabind/lua_include.hpp>``. If you for some reason need to include another
184 Lua header, you can modify this file.
193 #include <luabind/luabind.hpp>
197 std::cout << "hello world!\n";
200 extern "C" int init(lua_State* L)
202 using namespace luabind;
216 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
217 > loadlib('hello_world.dll', 'init')()
225 Everything that gets registered in Lua is registered in a namespace (Lua
226 tables) or in the global scope (called module). All registrations must be
227 surrounded by its scope. To define a module, the ``luabind::module`` class is
228 used. It is used like this::
235 This will register all declared functions or classes in the global namespace in
236 Lua. If you want to have a namespace for your module (like the standard
237 libraries) you can give a name to the constructor, like this::
239 module(L, "my_library")
244 Here all declarations will be put in the my_library table.
246 If you want nested namespaces you can use the ``luabind::namespace_`` class. It
247 works exactly as ``luabind::module`` except that it doesn't take a lua_State*
248 in it's constructor. An example of its usage could look like this::
250 module(L, "my_library")
256 // library-private declarations
260 As you might have figured out, the following declarations are equivalent::
264 namespace_("my_library")
273 module(L, "my_library")
278 Each declaration must be separated by a comma, like this::
285 .def(constructor<int, int>),
290 More about the actual declarations in the `Binding functions to Lua`_ and
291 `Binding classes to Lua`_ sections.
293 A word of caution, if you are in really bad need for performance, putting your
294 functions in tables will increase the lookup time.
297 Binding functions to Lua
298 ========================
300 To bind functions to Lua you use the function ``luabind::def()``. It has the
303 template<class F, class policies>
304 void def(const char* name, F f, const Policies&);
306 - name is the name the function will have within Lua.
307 - F is the function pointer you want to register.
308 - The Policies parameter is used to describe how parameters and return values
309 are treated by the function, this is an optional parameter. More on this in
310 the `policies`_ section.
312 An example usage could be if you want to register the function ``float
317 def("sin", &std::sin)
323 If you have more than one function with the same name, and want to register
324 them in Lua, you have to explicitly give the signature. This is to let C++ know
325 which function you refer to. For example, if you have two functions, ``int
326 f(const char*)`` and ``void f(int)``. ::
330 def("f", (int(*)(const char*)) &f),
331 def("f", (void(*)(int)) &f)
337 luabind will generate code that checks the Lua stack to see if the values there
338 can match your functions' signatures. It will handle implicit typecasts between
339 derived classes, and it will prefer matches with the least number of implicit
340 casts. In a function call, if the function is overloaded and there's no
341 overload that match the parameters better than the other, you have an
342 ambiguity. This will spawn a run-time error, stating that the function call is
343 ambiguous. A simple example of this is to register one function that takes an
344 int and one that takes a float. Since Lua don't distinguish between floats and
345 integers, both will always match.
347 Since all overloads are tested, it will always find the best match (not the
348 first match). This also means that it can handle situations where the only
349 difference in the signature is that one member function is const and the other
352 .. sidebar:: Ownership transfer
354 To correctly handle ownership transfer, create_a() would need an adopt
355 return value policy. More on this in the `Policies`_ section.
357 For example, if the following function and class is registered:
375 And the following Lua code is executed::
378 a1:f() -- the const version is called
381 a2:f() -- the non-const version is called
392 Calling Lua functions
393 ---------------------
395 To call a Lua function, you can either use ``call_function()``,
396 an ``object`` or ``functor``.
401 Ret call_function(lua_State* L, const char* name, ...)
403 Ret call_function(object const& obj, ...)
405 There are two overloads of the ``call_function`` function, one that calls
406 a function given its name, and one that takes an object that should be a Lua
407 value that can be called as a function.
409 The overload that takes a name can only call global Lua functions. The ...
410 represents a variable number of parameters that are sent to the Lua
411 function. This function call may throw ``luabind::error`` if the function
414 The return value isn't actually Ret (the template parameter), but a proxy
415 object that will do the function call. This enables you to give policies to the
416 call. You do this with the operator[]. You give the policies within the
417 brackets, like this::
419 int ret = call_function<int>(
422 , new complex_class()
425 If you want to pass a parameter as a reference, you have to wrap it with the
428 __ http://www.boost.org/doc/html/ref.html
432 int ret = call_function(L, "fun", boost::ref(val));
438 To start a Lua thread, you have to call ``lua_resume()``, this means that you
439 cannot use the previous function ``call_function()`` to start a thread. You have
445 Ret resume_function(lua_State* L, const char* name, ...)
447 Ret resume_function(object const& obj, ...)
454 Ret resume(lua_State* L, ...)
456 The first time you start the thread, you have to give it a function to execute. i.e. you
457 have to use ``resume_function``, when the Lua function yeilds, it will return the first
458 value passed in to ``lua_yield()``. When you want to continue the execution, you just call
459 ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
460 it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side.
462 For yielding C++-functions (without the support of passing data back and forth between the
463 Lua side and the c++ side), you can use the yield_ policy.
465 With the overload of ``resume_function`` that takes an object_, it is important that the
466 object was constructed with the thread as its ``lua_State*``. Like this:
470 lua_State* thread = lua_newthread(L);
471 object fun = get_global(**thread**)["my_thread_fun"];
472 resume_function(fun);
475 Binding classes to Lua
476 ======================
478 To register classes you use a class called ``class_``. Its name is supposed to
479 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
480 member function ``def()`` that is used to register member functions, operators,
481 constructors, enums and properties on the class. It will return its
482 this-pointer, to let you register more members directly.
484 Let's start with a simple example. Consider the following C++ class::
489 testclass(const std::string& s): m_string(s) {}
490 void print_string() { std::cout << m_string << "\n"; }
493 std::string m_string;
496 To register it with a Lua environment, write as follows (assuming you are using
501 class_<testclass>("testclass")
502 .def(constructor<const std::string&>())
503 .def("print_string", &testclass::print_string)
506 This will register the class with the name testclass and constructor that takes
507 a string as argument and one member function with the name ``print_string``.
511 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
512 > a = testclass('a string')
516 It is also possible to register free functions as member functions. The
517 requirement on the function is that it takes a pointer, const pointer,
518 reference or const reference to the class type as the first parameter. The rest
519 of the parameters are the ones that are visible in Lua, while the object
520 pointer is given as the first parameter. If we have the following C++ code::
527 int plus(A* o, int v) { return o->a + v; }
529 You can register ``plus()`` as if it was a member function of A like this::
534 ``plus()`` can now be called as a member function on A with one parameter, int.
535 If the object pointer parameter is const, the function will act as if it was a
536 const member function (it can be called on const objects).
542 To register a global data member with a class is easily done. Consider the
550 This class is registered like this::
555 .def_readwrite("a", &A::a)
558 This gives read and write access to the member variable ``A::a``. It is also
559 possible to register attributes with read-only access::
564 .def_readonly("a", &A::a)
567 You can also register getter and setter functions and make them look as if they
568 were a public data member. Consider the following class::
573 void set_a(int x) { a = x; }
574 int get_a() const { return a; }
580 It can be registered as if it had a public data member a like this::
583 .property("a", &A::get_a, &A::set_a)
585 This way the ``get_a()`` and ``set_a()`` functions will be called instead of
586 just writing to the data member. If you want to make it read only you can just
587 omit the last parameter.
593 If your class contains enumerated constants (enums), you can register them as
594 well to make them available in Lua. Note that they will not be type safe, all
595 enums are integers in Lua, and all functions that takes an enum, will accept
596 any integer. You register them like this::
604 value("my_2nd_enum", 7),
605 value("another_enum", 6)
609 In Lua they are accessed like any data member, except that they are read-only
610 and reached on the class itself rather than on an instance of the class.
614 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
617 > print(A.another_enum)
624 The mechanism for registering operators on your class is pretty simple. You use
625 a global name ``luabind::self`` to refer to the class itself and then you just
626 write the operator expression inside the ``def()`` call. This class::
630 vec operator+(int s);
633 Is registered like this:
640 .def(**self + int()**)
643 This will work regardless if your plus operator is defined inside your class or
646 If you operator is const (or, when defined as a free function, takes a const
647 reference to the class itself) you have to use ``const_self`` instead of
655 .def(**const_self** + int())
658 The operators supported are those available in Lua:
662 + - \* / == != < <= > >=
664 This means, no in-place operators. The equality operator (``==``) has a little
665 hitch; it will not be called if the references are equal. This means that the
666 ``==`` operator has to do pretty much what's it's expected to do.
668 In the above example the other operand type is instantiated by writing
669 ``int()``. If the operand type is a complex type that cannot easily be
670 instantiated you can wrap the type in a class called ``other<>``. For example:
672 To register this class, we don't want to instantiate a string just to register
679 vec operator+(std::string);
682 Instead we use the ``other<>`` wrapper like this:
689 .def(self + **other<std::string>()**)
692 To register an application operator:
699 .def( **self(int())** )
702 There's one special operator. In Lua it's called ``__tostring``, it's not
703 really an operator. It is used for converting objects to strings in a standard
704 way in Lua. If you register this functionality, you will be able to use the lua
705 standard function ``tostring()`` for converting you object to a string.
707 To implement this operator in C++ you should supply an ``operator<<`` for
708 ostream. Like this example:
713 std::ostream& operator<<(std::ostream&, number&);
719 class_<number>("number")
720 .def(**tostring(self)**)
724 Nested scopes and static functions
725 ----------------------------------
727 It is possible to add nested scopes to a class. This is useful when you need
728 to wrap a nested class, or a static function.
736 class_<inner>("nested"),
740 It's also possible to add namespaces to classes using the same syntax.
746 If you want to register classes that derives from other classes, you can
747 specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
748 following hierarchy::
753 Would be registered like this::
761 If you have multiple inheritance you can specify more than one base. If B would
762 also derive from a class C, it would be registered like this::
766 class_<B, bases<A, C> >("B")
769 Note that you can omit ``bases<>`` when using single inheritance.
772 If you don't specify that classes derive from each other, luabind will not
773 be able to implicitly cast pointers between the types.
779 When you register a class you can tell luabind that all instances of that class
780 should be held by some kind of smart pointer (boost::shared_ptr for instance).
781 You do this by giving the holder type as an extra template parameter to
782 the ``class_`` you are constructing, like this::
786 class_<A, boost::shared_ptr<A> >("A")
789 You also have to supply two functions for your smart pointer. One that returns
790 the type of const version of the smart pointer type (boost::shared_ptr<const A>
791 in this case). And one function that extracts the raw pointer from the smart
792 pointer. The first function is needed because luabind has to allow the
793 non-const -> conversion when passing values from Lua to C++. The second
794 function is needed when Lua calls member functions on held types, the this
795 pointer must be a raw pointer, it is also needed to allow the smart_pointer ->
796 raw_pointer conversion from Lua to C++. They look like this::
801 T* get_pointer(boost::shared_ptr<T> const& p)
807 boost::shared_ptr<const A>*
808 get_const_holder(boost::shared_ptr<A>*)
814 The conversion that works are (given that B is a base class of A):
816 .. topic:: From Lua to C++
818 ========================= ========================
820 ========================= ========================
821 ``holder_type<A>`` ``A*``
822 ``holder_type<A>`` ``B*``
823 ``holder_type<A>`` ``A const*``
824 ``holder_type<A>`` ``B const*``
825 ``holder_type<A>`` ``holder_type<A>``
826 ``holder_type<A>`` ``holder_type<A const>``
827 ``holder_type<A const>`` ``A const*``
828 ``holder_type<A const>`` ``B const*``
829 ``holder_type<A const>`` ``holder_type<A const>``
830 ========================= ========================
832 .. topic:: From C++ to Lua
834 =============================== ========================
836 =============================== ========================
837 ``holder_type<A>`` ``holder_type<A>``
838 ``holder_type<A const>`` ``holder_type<A const>``
839 ``holder_type<A> const&`` ``holder_type<A>``
840 ``holder_type<A const> const&`` ``holder_type<A const>``
841 =============================== ========================
843 When using a holder type, it can be useful to know if the pointer is valid. For
844 example when using std::auto_ptr, the holder will be invalidated when passed as
845 a parameter to a function. For this purpose there is a member of all object
846 instances in luabind: ``__ok``. ::
849 void f(std::auto_ptr<X>);
853 class_<X, std::auto_ptr<X> >("X")
854 .def(constructor<>()),
861 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
871 Since functions have to be able to take Lua values (of variable type) we need a
872 wrapper around them. This wrapper is called ``luabind::object``. If the
873 function you register takes an object, it will match any Lua value. To use it,
874 you need to include ``luabind/object.hpp``.
885 class array_iterator;
888 object(lua_State\*, T const& value);
889 object(object const&);
895 iterator begin() const;
896 iterator end() const;
897 raw_iterator raw_begin() const;
898 raw_iterator raw_end() const;
899 array_iterator abegin() const;
900 array_iterator aend() const;
903 lua_State\* lua_state() const;
904 void pushvalue() const;
905 bool is_valid() const;
906 operator safe_bool_type() const;
909 *implementation-defined* operator[](Key const&);
912 object at(Key const&) const;
915 object raw_at(Key const&) const;
918 object& operator=(T const&);
919 object& operator=(object const&);
922 bool operator==(T const&) const;
923 bool operator==(object const&) const;
924 bool operator<(object const&) const;
925 bool operator<=(object const&) const;
926 bool operator>(object const&) const;
927 bool operator>=(object const&) const;
928 bool operator!=(object const&) const;
933 *implementation-defined* operator()();
936 *implementation-defined* operator()(A0 const& a0);
938 template<class A0, class A1>
939 *implementation-defined* operator()(A0 const& a0, A1 const& a1);
944 When you have a Lua object, you can assign it a new value with the assignment
945 operator (=). When you do this, the ``default_policy`` will be used to make the
946 conversion from C++ value to Lua. If your ``luabind::object`` is a table you
947 can access its members through the operator[] or the iterators. The value
948 returned from the operator[] is a proxy object that can be used both for
949 reading and writing values into the table (using operator=). Note that it is
950 impossible to know if a Lua value is indexable or not (lua_gettable doesn't
951 fail, it succeeds or crashes). This means that if you're trying to index
952 something that cannot be indexed, you're on your own. Lua will call its
953 ``panic()`` function (you can define your own panic function using
954 ``lua_setpanicf``). The ``at()`` and ``raw_at()`` functions returns the value at
955 the given table position (like operator[] but only for reading).
957 The ordinary ``object::iterator`` uses lua_gettable to extract the values from
958 the table, the standard way that will invoke metamethods if any. The
959 ``object::raw_iterator`` uses lua_rawget and ``object::array_iterator`` uses
960 lua_rawgeti. The latter will only iterate over numberical keys starting at 1
961 and continue until the first nil value.
963 The ``lua_state()`` function returns the Lua state where this object is stored.
964 If you want to manipulate the object with Lua functions directly you can push
965 it onto the Lua stack by calling ``pushvalue()``. And set the object's value by
966 calling ``set()``, which will pop the top value from the Lua stack and assign
969 The operator== will call lua_equal() on the operands and return its result.
971 The ``type()`` member function will return the Lua type of the object. It will
972 return the same values as lua_type().
974 The ``is_valid()`` function tells you whether the object has been initialized
975 or not. When created with its default constructor, objects are invalid. To make
976 an object valid, you can assign it a value. If you want to invalidate an object
977 you can simply assign it an invalid object.
979 .. So what? implementation detail, leave out of docs
980 isn't really an implicit cast to bool, but an implicit cast
981 to a member pointer, since member pointers don't have any arithmetic operators
982 on them (which can cause hard to find errors). The functionality of the cast
985 The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
986 that these snippets are equivalent::
1004 The application operator will call the value as if it was a function. You can
1005 give it any number of parameters (currently the ``default_policy`` will be used
1006 for the conversion). The returned object refers to the return value (currently
1007 only one return value is supported). This operator may throw ``luabind::error``
1008 if the function call fails. If you want to specify policies to your function
1009 call, you can use index-operator (operator[]) on the function call, and give
1010 the policies within the [ and ]. Like this::
1015 , new my_complex_structure(6)
1018 This tells luabind to make Lua adopt the ownership and responsibility for the
1019 pointer passed in to the lua-function.
1021 It's important that all instances of object have been destructed by the time
1022 the Lua state is closed. The object will keep a pointer to the lua state and
1023 release its Lua object in its destructor.
1025 Here's an example of how a function can use a table::
1027 void my_function(const object& table)
1029 if (table.type() == LUA_TTABLE)
1031 table["time"] = std::clock();
1032 table["name"] = std::rand() < 500 ? "unusual" : "usual";
1034 std::cout << object_cast<std::string>(table[5]) << "\n";
1038 If you take a ``luabind::object`` as a parameter to a function, any Lua value
1039 will match that parameter. That's why we have to make sure it's a table before
1046 The iterators, that are returned by ``begin()`` and ``end()`` (and their
1047 variants) are (almost) models of the ForwardIterator concept. The exception
1048 is that post increment doesn't exist on them.
1054 class object::iterator
1057 iterator(const iterator&);
1059 iterator& operator++();
1060 bool operator!=(const iterator&) const;
1061 iterator& operator=(const iterator&);
1065 *implementation-defined* operator*();
1068 The implementation defined return value from the dereference operator is a
1069 proxy object that can be used as if it was an object, it can also be used to
1070 assign the specific table entry with a new value. If you want to assign a value
1071 to an entry pointed to by an iterator, just use the assignment operator on the
1072 dereferenced iterator::
1076 The ``key()`` member returns the key used by the iterator when indexing the
1077 associated Lua table.
1083 There are a couple of functions related to objects and tables. ::
1085 T object_cast<T>(object const&);
1086 T object_cast<T>(object const&, Policies);
1088 boost::optional<T> object_cast_nothrow<T>(object const&);
1089 boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
1095 The ``functor`` class is similar to object, with the exception that it can only
1096 be used to store functions. If you take it as a parameter, it will only match
1099 To use it you need to include its header::
1101 #include <luabind/functor.hpp>
1103 It takes one template parameter, the return value of the Lua function it
1104 represents. Currently the functor can have at most one return value (unlike Lua
1116 functor(lua_State\*, char const* name);
1117 functor(functor const&);
1120 bool is_valid() const;
1121 operator safe_bool_type() const;
1124 lua_State\* lua_state() const;
1125 void pushvalue() const;
1127 bool operator==(functor<Ret> const&);
1128 bool operator!=(functor<Ret> const&);
1130 *implementation-defined* operator()() const;
1133 *implementation-defined* operator()(A0 const&) const;
1135 template<class A0, class A1>
1136 *implementation-defined* operator()(A0 const&, A1 const&) const;
1141 The application operator takes any parameters. The parameters are converted
1142 into Lua and the function is called. The return value will act as if it was the
1143 type Ret, with the exception that you can use the return value to give policies
1144 to the call. You do this the same way as you do with objects, using the
1145 operator[], and giving the policies inside the brackets.
1147 The ``is_valid()`` function works just like the one on object, it tells you if
1148 the functor has been assigned with a valid Lua function. The ``operator
1149 safe_bool_type()`` is an alias for this member function and also works just as
1150 the one found in object.
1152 For example, if you have the following Lua function::
1158 You can expose it to C++ like this::
1160 functor<int> f(L, "f");
1162 std::cout << f(3, 5) << "\n";
1164 This will print out the sum of 3 and 5. Note that you can pass any parameters
1165 to the application operator of ``luabind::functor``, this is because lua
1166 doesn't have signatures for its functions. All Lua functions take any number of
1167 parameters of any type.
1169 If we have a C++ function that takes a ``luabind::functor`` and registers it,
1170 it will accept Lua functions passed to it. This enables us to expose APIs that
1171 requires you to register callbacks. For example, if your C++ API looks like
1174 void set_callback(void(*)(int, int));
1176 And you want to expose it to Lua, you have to wrap the call to the Lua
1177 function inside a real C++ function, like this::
1179 functor<void> lua_callback;
1181 void callback_wrapper(int a, int b)
1186 void set_callback_wrapper(const functor<void>& f)
1189 set_callback(&callback_wrapper);
1192 And then register ``set_callback_wrapper`` instead of registering
1193 ``set_callback``. This will have the effect that when one tries to register the
1194 callback from Lua, your ``set_callback_wrapper`` will be called instead and
1195 first set the Lua functor to the given function. It will then call the real
1196 ``set_callback`` with the ``callback_wrapper``. The ``callback_wrapper`` will
1197 be called whenever the callback should be called, and it will simply call the
1198 Lua function that we registered.
1200 You can also use ``object_cast`` to cast an object to a functor.
1202 ``reset`` on ``functor`` will invalidate the functor (and remove any references
1203 to its Lua value). If the functor object has longer lifetime than the lua state
1204 (e.g. if it's a global).
1207 Defining classes in Lua
1208 =======================
1210 In addition to binding C++ functions and classes with Lua, luabind also provide
1211 an OO-system in Lua. ::
1213 class 'lua_testclass'
1215 function lua_testclass:__init(name)
1219 function lua_testclass:print()
1223 a = lua_testclass('example')
1227 Inheritance can be used between lua-classes::
1229 class 'derived' (lua_testclass)
1231 function derived:__init() super('derived name')
1234 function derived:print()
1235 print('Derived:print() -> ')
1236 lua_testclass.print(self)
1239 Here the ``super`` keyword is used in the constructor to initialize the base
1240 class. The user is required to call ``super`` first in the constructor.
1242 As you can see in this example, you can call the base class member functions.
1243 You can find all member functions in the base class, but you will have to give
1244 the this-pointer (``self``) as first argument.
1250 It is also possible to derive Lua classes from C++ classes, and override
1251 virtual functions with Lua functions. To do this we have to create a wrapper
1252 class for our C++ base class. This is the class that will hold the Lua object
1253 when we instantiate a Lua class.
1261 { std::cout << s << "\n"; }
1263 virtual void f(int a)
1264 { std::cout << "f(" << a << ")\n"; }
1267 struct base_wrapper : base, luabind::wrap_base
1269 base_wrapper(const char* s)
1273 virtual void f(int a)
1278 static void default_f(base* ptr, int a)
1280 return ptr->base::f(a);
1288 class_<base, base_wrapper>("base")
1289 .def(constructor<const char*>())
1290 .def("f", &base_wrapper::f, &base_wrapper::default_f)
1294 Since visual studio 6.5 doesn't support explicit template parameters
1295 to member functions, instead of using the member function ``call()``
1296 you call a free function ``call_member()`` and pass the this-pointer
1299 Note that if you have both base classes and a base class wrapper, you must give
1300 both bases and the base class wrapper type as template parameter to
1301 ``class_`` (as done in the example above). The order in which you specify
1302 them is not important. You must also register both the static version and the
1303 virtual version of the function from the wrapper, this is necessary in order
1304 to allow luabind to use both dynamic and static dispatch when calling the function.
1307 It is extremely important that the signatures of the static (default) function
1308 is identical to the virtual function. The fact that one of them is a free
1309 function and the other a member function doesn't matter, but the parameters
1310 as seen from lua must match. It would not have worked if the static function
1311 took a ``base_wrapper*`` as its first argument, since the virtual function
1312 takes a ``base*`` as its first argument (its this pointer). There's currently
1313 no check in luabind to make sure the signatures match.
1315 If we didn't have a class wrapper, it would not be possible to pass a Lua class
1316 back to C++. Since the entry points of the virtual functions would still point
1317 to the C++ base class, and not to the functions defined in Lua. That's why we
1318 need one function that calls the base class' real function (used if the lua
1319 class doesn't redefine it) and one virtual function that dispatches the call
1320 into luabind, to allow it to select if a Lua function should be called, or if
1321 the original function should be called. If you don't intend to derive from a
1322 C++ class, or if it doesn't have any virtual member functions, you can register
1323 it without a class wrapper.
1325 You don't need to have a class wrapper in order to derive from a class, but if
1326 it has virtual functions you may have silent errors.
1328 .. Unnecessary? The rule of thumb is:
1329 If your class has virtual functions, create a wrapper type, if it doesn't
1330 don't create a wrapper type.
1332 The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference
1333 that will hold the Lua instance of the object to make it possible to dispatch
1334 virtual function calls into Lua. This is done through an overloaded member function::
1337 Ret call(char const* name, ...)
1339 Its used in a similar way as ``call_function``, with the exception that it doesn't
1340 take a ``lua_State`` pointer, and the name is a member function in the Lua class.
1344 The current implementation of ``call_member`` is not able to distinguish const
1345 member functions from non-const. If you have a situation where you have an overloaded
1346 virtual function where the only difference in their signatures is their constness, the
1347 wrong overload will be called by ``call_member``. This is rarely the case though.
1352 When a pointer or reference to a registered class with a wrapper is passed
1353 to Lua, luabind will query for it's dynamic type. If the dynamic type
1354 inherits from ``wrap_base``, object identity is preserved.
1359 struct A_wrap : A, wrap_base { .. };
1361 A* f(A* ptr) { return ptr; }
1365 class_<A, A_wrap>("A"),
1373 > assert(x == f(x)) -- object identity is preserved when object is
1374 -- passed through C++
1376 This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is
1379 Overloading operators
1380 ---------------------
1382 You can overload most operators in Lua for your classes. You do this by simply
1383 declaring a member function with the same name as an operator (the name of the
1384 metamethods in Lua). The operators you can overload are:
1398 ``__tostring`` isn't really an operator, but it's the metamethod that is called
1399 by the standard library's ``tostring()`` function. There's one strange behavior
1400 regarding binary operators. You are not guaranteed that the self pointer you
1401 get actually refers to an instance of your class. This is because Lua doesn't
1402 distinguish the two cases where you get the other operand as left hand value or
1403 right hand value. Consider the following examples::
1407 function my_class:__init(v)
1411 function my_class:__sub(v)
1412 return my_class(self.val - v.val)
1415 function my_class:__tostring()
1419 This will work well as long as you only subtracts instances of my_class with
1420 each other. But If you want to be able to subtract ordinary numbers from your
1421 class too, you have to manually check the type of both operands, including the
1424 function my_class:__sub(v)
1425 if (type(self) == 'number') then
1426 return my_class(self - v.val)
1428 elseif (type(v) == 'number') then
1429 return my_class(self.val - v)
1432 -- assume both operands are instances of my_class
1433 return my_class(self.val - v.val)
1438 The reason why ``__sub`` is used as an example is because subtraction is not
1439 commutative (the order of the operands matter). That's why luabind cannot
1440 change order of the operands to make the self reference always refer to the
1441 actual class instance.
1443 If you have two different Lua classes with an overloaded operator, the operator
1444 of the right hand side type will be called. If the other operand is a C++ class
1445 with the same operator overloaded, it will be prioritized over the Lua class'
1446 operator. If none of the C++ overloads matches, the Lua class operator will be
1453 If an object needs to perform actions when it's collected we provide a
1454 ``__finalize`` function that can be overridden in lua-classes. The
1455 ``__finalize`` functions will be called on all classes in the inheritance
1456 chain, starting with the most derived type. ::
1460 function lua_testclass:__finalize()
1461 -- called when the an object is collected
1468 If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and
1469 you derive from them in lua, they may be sliced. Meaning, if an object
1470 is passed into C++ as a pointer to its base class, the lua part will be
1471 separated from the C++ base part. This means that if you call virtual
1472 functions on that C++ object, thyey will not be dispatched to the lua
1473 class. It also means that if you adopt the object, the lua part will be
1478 +--------------------+
1479 | C++ object | <- ownership of this part is transferred
1480 | | to c++ when adopted
1481 +--------------------+
1482 | lua class instance | <- this part is garbage collected when
1483 | and lua members | instance is adopted, since it cannot
1484 +--------------------+ be held by c++.
1487 The problem can be illustrated by this example::
1491 A* filter_a(A* a) { return a; }
1492 void adopt_a(A* a) { delete a; }
1497 using namespace luabind;
1502 def("filter_a", &filter_a),
1503 def("adopt_a", &adopt_a, adopt(_1))
1513 In this example, lua cannot know that ``b`` actually is the same object as
1514 ``a``, and it will therefore consider the object to be owned by the C++ side.
1515 When the ``b`` pointer then is adopted, a runtime error will be raised because
1516 an object not owned by lua is being adopted to C++.
1518 If you have a wrapper for your class, none of this will happen, see
1525 If any of the functions you register throws an exception when called, that
1526 exception will be caught by luabind and converted to an error string and
1527 ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
1528 ``const char*`` the string that is pushed on the Lua stack, as error message,
1529 will be the string returned by ``std::exception::what()`` or the string itself
1530 respectively. If the exception is unknown, a generic string saying that the
1531 function threw an exception will be pushed.
1533 Exceptions thrown from user defined functions have to be caught by luabind. If
1534 they weren't they would be thrown through Lua itself, which is usually compiled
1535 as C code and doesn't support the stack-unwinding that exceptions imply.
1537 Any function that invokes Lua code may throw ``luabind::error``. This exception
1538 means that a Lua run-time error occurred. The error message is found on top of
1539 the Lua stack. The reason why the exception doesn't contain the error string
1540 itself is because it would then require heap allocation which may fail. If an
1541 exception class throws an exception while it is being thrown itself, the
1542 application will be terminated.
1544 Error's synopsis is::
1546 class error : public std::exception
1550 lua_State* state() const throw();
1551 virtual const char* what() const throw();
1554 The state function returns a pointer to the Lua state in which the error was
1555 thrown. This pointer may be invalid if you catch this exception after the lua
1556 state is destructed. If the Lua state is valid you can use it to retrieve the
1557 error message from the top of the Lua stack.
1559 An example of where the Lua state pointer may point to an invalid state
1564 lua_state(lua_State* L): m_L(L) {}
1565 ~lua_state() { lua_close(m_L); }
1566 operator lua_State*() { return m_L; }
1574 lua_state L = lua_open();
1577 catch(luabind::error& e)
1579 lua_State* L = e.state();
1580 // L will now point to the destructed
1581 // Lua state and be invalid
1586 There's another exception that luabind may throw: ``luabind::cast_failed``,
1587 this exception is thrown from ``call_function<>``, ``call_member<>`` or when
1588 ``functor<>`` is invoked. It means that the return value from the Lua function
1589 couldn't be converted to a C++ value. It is also thrown from ``object_cast<>``
1590 if the cast cannot be made.
1592 The synopsis for ``luabind::cast_failed`` is::
1594 class cast_failed : public std::exception
1597 cast_failed(lua_State*);
1598 lua_State* state() const throw();
1599 LUABIND_TYPE_INFO info() const throw();
1600 virtual const char* what() const throw();
1603 Again, the state member function returns a pointer to the Lua state where the
1604 error occurred. See the example above to see where this pointer may be invalid.
1606 The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
1607 defaults to a ``const std::type_info*``. This type info describes the type that
1608 we tried to cast a Lua value to.
1610 If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
1611 thrown, instead you can set two callback functions that are called instead.
1612 These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
1616 luabind::set_error_callback(void(*)(lua_State*))
1618 The function you set will be called when a runtime-error occur in Lua code. You
1619 can find an error message on top of the Lua stack. This function is not
1620 expected to return, if it does luabind will call ``std::terminate()``.
1624 luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1626 The function you set is called instead of throwing ``cast_failed``. This function
1627 is not expected to return, if it does luabind will call ``std::terminate()``.
1633 Sometimes it is necessary to control how luabind passes arguments and return
1634 value, to do this we have policies. All policies use an index to associate
1635 them with an argument in the function signature. These indices are ``result``
1636 and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers
1637 to the ``this`` pointer.
1639 .. contents:: Policies currently implemented
1643 .. include:: adopt.rst
1644 .. include:: dependency.rst
1645 .. include:: out_value.rst
1646 .. include:: pure_out_value.rst
1647 .. include:: return_reference_to.rst
1648 .. include:: copy.rst
1649 .. include:: discard_result.rst
1650 .. include:: return_stl_iterator.rst
1651 .. include:: raw.rst
1652 .. include:: yield.rst
1654 .. old policies section
1655 ===================================================
1660 This will make a copy of the parameter. This is the default behavior when
1661 passing parameters by-value. Note that this can only be used when passing from
1662 C++ to Lua. This policy requires that the parameter type has a copy
1665 To use this policy you need to include ``luabind/copy_policy.hpp``.
1671 This will transfer ownership of the parameter.
1673 Consider making a factory function in C++ and exposing it to lua::
1684 def("create_base", create_base)
1687 Here we need to make sure Lua understands that it should adopt the pointer
1688 returned by the factory-function. This can be done using the adopt-policy.
1694 def(L, "create_base", adopt(return_value))
1697 To specify multiple policies we just separate them with '+'.
1701 base* set_and_get_new(base* ptr)
1703 base_ptrs.push_back(ptr);
1709 def("set_and_get_new", &set_and_get_new,
1710 adopt(return_value) + adopt(_1))
1713 When Lua adopts a pointer, it will call delete on it. This means that it cannot
1714 adopt pointers allocated with another allocator than new (no malloc for
1717 To use this policy you need to include ``luabind/adopt_policy.hpp``.
1723 The dependency policy is used to create life-time dependencies between values.
1724 Consider the following example::
1730 const B& get_member()
1736 When wrapping this class, we would do something like::
1741 .def(constructor<>())
1742 .def("get_member", &A::get_member)
1746 However, since the return value of get_member is a reference to a member of A,
1747 this will create some life-time issues. For example::
1749 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1751 b = a:get_member() -- b points to a member of a
1753 collectgarbage(0) -- since there are no references left to a, it is
1755 -- at this point, b is pointing into a removed object
1757 When using the dependency-policy, it is possible to tell luabind to tie the
1758 lifetime of one object to another, like this::
1763 .def(constructor<>())
1764 .def("get_member", &A::get_member, dependency(result, _1))
1767 This will create a dependency between the return-value of the function, and the
1768 self-object. This means that the self-object will be kept alive as long as the
1769 result is still alive. ::
1771 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1773 b = a:get_member() -- b points to a member of a
1775 collectgarbage(0) -- a is dependent on b, so it isn't removed
1777 collectgarbage(0) -- all dependencies to a gone, a is removed
1779 To use this policy you need to include ``luabind/dependency_policy.hpp``.
1785 It is very common to return references to arguments or the this-pointer to
1786 allow for chaining in C++.
1801 When luabind generates code for this, it will create a new object for the
1802 return-value, pointing to the self-object. This isn't a problem, but could be a
1803 bit inefficient. When using the return_reference_to-policy we have the ability
1804 to tell luabind that the return-value is already on the Lua stack.
1811 .def(constructor<>())
1812 .def("set", &A::set, return_reference_to(_1))
1815 Instead of creating a new object, luabind will just copy the object that is
1816 already on the stack.
1819 This policy ignores all type information and should be used only it
1820 situations where the parameter type is a perfect match to the
1821 return-type (such as in the example).
1823 To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
1829 This policy makes it possible to wrap functions that take non const references
1830 as its parameters with the intention to write return values to them.
1834 void f(float& val) { val = val + 10.f; }
1840 void f(float* val) { *val = *val + 10.f; }
1842 Can be wrapped by doing::
1846 def("f", &f, out_value(_1))
1849 When invoking this function from Lua it will return the value assigned to its
1854 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1859 When this policy is used in conjunction with user define types we often need
1860 to do ownership transfers.
1866 void f1(A*& obj) { obj = new A(); }
1867 void f2(A** obj) { *obj = new A(); }
1869 Here we need to make sure luabind takes control over object returned, for
1870 this we use the adopt policy::
1875 def("f1", &f1, out_value(_1, adopt(_2)))
1876 def("f2", &f2, out_value(_1, adopt(_2)))
1879 Here we are using adopt as an internal policy to out_value. The index
1880 specified, _2, means adopt will be used to convert the value back to Lua.
1881 Using _1 means the policy will be used when converting from Lua to C++.
1883 To use this policy you need to include ``luabind/out_value_policy.hpp``.
1888 This policy works in exactly the same way as out_value, except that it
1889 replaces the parameters with default-constructed objects.
1893 void get(float& x, float& y)
1904 pure_out_value(_1) + pure_out_value(_2))
1909 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1914 Like out_value, it is possible to specify an internal policy used then
1915 converting the values back to Lua.
1919 void get(test_class*& obj)
1921 obj = new test_class();
1928 def("get", &get, pure_out_value(_1, adopt(_1)))
1935 This is a very simple policy which makes it possible to throw away
1936 the value returned by a C++ function, instead of converting it to
1937 Lua. This example makes sure the this reference never gets converted
1944 simple& set_name(const std::string& n)
1957 class_<simple>("simple")
1958 .def("set_name", &simple::set_name, discard_result)
1961 To use this policy you need to include ``luabind/discard_result_policy.hpp``.
1967 This policy converts an STL container to a generator function that can be used
1968 in Lua to iterate over the container. It works on any container that defines
1969 ``begin()`` and ``end()`` member functions (they have to return iterators). It
1970 can be used like this::
1974 std::vector<std::string> names;
1981 .def_readwrite("names", &A::names, return_stl_iterator)
1984 The Lua code to iterate over the container::
1988 for name in a.names do
1993 To use this policy you need to include ``luabind/iterator_policy.hpp``.
1999 This policy will cause the function to always yield the current thread when
2000 returning. See the Lua manual for restrictions on yield.
2003 Splitting up the registration
2004 =============================
2006 It is possible to split up a module registration into several
2007 translation units without making each registration dependent
2008 on the module it's being registered in.
2012 luabind::scope register_a()
2022 luabind::scope register_b()
2032 luabind::scope register_a();
2033 luabind::scope register_b();
2035 void register_module(lua_State* L)
2048 As mentioned in the `Lua documentation`_, it is possible to pass an
2049 error handler function to ``lua_pcall()``. Luabind makes use of
2050 ``lua_pcall()`` internally when calling methods and functions. It is
2051 possible to set the error handler function that Luabind will use
2054 typedef void(*pcall_callback_fun)(lua_State*);
2055 void set_pcall_callback(pcall_callback_fun fn);
2057 This is primarily useful for adding more information to the error message
2058 returned by a failed protected call.
2060 .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
2065 There are a number of configuration options available when building luabind.
2066 It is very important that your project has the exact same conmfiguration
2067 options as the ones given when the library was build! The exceptions are the
2068 ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based
2069 options and only matters when you use the library (which means they can
2070 differ from the settings of the library).
2072 The default settings which will be used if no other settings are given
2073 can be found in ``luabind/config.hpp``.
2075 If you want to change the settings of the library, you can modify the
2076 config file. It is included and used by all makefiles. You can change paths
2077 to Lua and boost in there as well.
2080 Controls the maximum arity of functions that are registered with luabind.
2081 You can't register functions that takes more parameters than the number
2082 this macro is set to. It defaults to 5, so, if your functions have greater
2083 arity you have to redefine it. A high limit will increase compilation time.
2086 Controls the maximum number of classes one class can derive from in
2087 luabind (the number of classes specified within ``bases<>``).
2088 ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase
2091 LUABIND_NO_ERROR_CHECKING
2092 If this macro is defined, all the Lua code is expected only to make legal
2093 calls. If illegal function calls are made (e.g. giving parameters that
2094 doesn't match the function signature) they will not be detected by luabind
2095 and the application will probably crash. Error checking could be disabled
2096 when shipping a release build (given that no end-user has access to write
2097 custom Lua code). Note that function parameter matching will be done if a
2098 function is overloaded, since otherwise it's impossible to know which one
2099 was called. Functions will still be able to throw exceptions when error
2100 checking is disabled.
2102 If a functions throws an exception it will be caught by luabind and
2103 propagated with ``lua_error()``.
2105 LUABIND_NO_EXCEPTIONS
2106 This define will disable all usage of try, catch and throw in luabind.
2107 This will in many cases disable run-time errors, when performing invalid
2108 casts or calling Lua functions that fails or returns values that cannot
2109 be converted by the given policy. luabind requires that no function called
2110 directly or indirectly by luabind throws an exception (throwing exceptions
2111 through Lua has undefined behavior).
2113 Where exceptions are the only way to get an error report from luabind,
2114 they will be replaced with calls to the callback functions set with
2115 ``set_error_callback()`` and ``set_cast_failed_callback()``.
2118 If you want to link dynamically against Lua, you can set this define to
2119 the import-keyword on your compiler and platform. On windows in devstudio
2120 this should be ``__declspec(dllimport)`` if you want to link against Lua
2123 LUABIND_EXPORT, LUABIND_IMPORT
2124 If you want to link against luabind as a dll (in devstudio), you can
2125 define ``LUABIND_EXPORT`` to ``__declspec(dllexport)`` and
2126 ``LUABIND_IMPORT`` to ``__declspec(dllimport)``.
2127 Note that you have to link against Lua as a dll aswell, to make it work.
2130 You can define this if you don't want luabind to use ``dynamic_cast<>``.
2131 It will disable `Object identity`_.
2133 LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO
2134 If you don't want to use the RTTI supplied by C++ you can supply your own
2135 type-info structure with the ``LUABIND_TYPE_INFO`` define. Your type-info
2136 structure must be copyable and must be able to compare itself against
2137 other type-info structures. You supply the compare function through the
2138 ``LUABIND_TYPE_INFO_EQUAL()`` define. It should compare the two type-info
2139 structures it is given and return true if they represent the same type and
2140 false otherwise. You also have to supply a function to generate your
2141 type-info structure. You do this through the ``LUABIND_TYPEID()`` define.
2142 It should return your type-info structure and it takes a type as its
2143 parameter. That is, a compile time parameter.
2144 ``LUABIND_INVALID_TYPE_INFO`` macro should be defined to an invalid type.
2145 No other type should be able to produce this type info. To use it you
2146 probably have to make a traits class with specializations for all classes
2147 that you have type-info for. Like this::
2153 template<class T> struct typeinfo_trait;
2155 template<> struct typeinfo_trait<A> { enum { type_id = 0 }; };
2156 template<> struct typeinfo_trait<B> { enum { type_id = 1 }; };
2157 template<> struct typeinfo_trait<C> { enum { type_id = 2 }; };
2159 If you have set up your own RTTI system like this (by using integers to
2160 identify types) you can have luabind use it with the following defines::
2162 #define LUABIND_TYPE_INFO const std::type_info*
2163 #define LUABIND_TYPEID(t) &typeid(t)
2164 #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
2165 #define LUABIND_INVALID_TYPE_INFO &typeid(detail::null_type)
2167 Currently the type given through ``LUABIND_TYPE_INFO`` must be less-than
2171 This define will disable all asserts and should be defined in a release
2175 Implementation notes
2176 ====================
2178 The classes and objects are implemented as user data in Lua. To make sure that
2179 the user data really is the internal structure it is supposed to be, we tag
2180 their metatables. A user data who's metatable contains a boolean member named
2181 ``__luabind_classrep`` is expected to be a class exported by luabind. A user
2182 data who's metatable contains a boolean member named ``__luabind_class`` is
2183 expected to be an instantiation of a luabind class.
2185 This means that if you make your own user data and tags its metatable with the
2186 exact same names, you can very easily fool luabind and crash the application.
2188 In the Lua registry, luabind keeps an entry called ``__luabind_classes``. It
2189 should not be removed or overwritten.
2191 In the global table, a variable called ``super`` is used every time a
2192 constructor in a lua-class is called. This is to make it easy for that
2193 constructor to call its base class' constructor. So, if you have a global
2194 variable named super it may be overwritten. This is probably not the best
2195 solution, and this restriction may be removed in the future.
2197 Luabind uses two upvalues for functions that it registers. The first is a
2198 userdata containing a list of overloads for the function, the other is a light
2199 userdata with the value 0x1337, this last value is used to identify functions
2200 registered by luabind. It should be virtually impossible to have such a pointer
2201 as secondary upvalue by pure chance. This means, if you are trying to replace
2202 an existing function with a luabind function, luabind will see that the
2203 secondary upvalue isn't the magic id number and replace it. If it can identify
2204 the function to be a luabind function, it won't replace it, but rather add
2205 another overload to it.
2207 Inside the luabind namespace, there's another namespace called detail. This
2208 namespace contains non-public classes and are not supposed to be used directly.
2214 - .. parsed-literal::
2216 the attribute '*class-name.attribute-name*' is read only
2218 There is no data member named *attribute-name* in the class *class-name*,
2219 or there's no setter-method registered on that property name. See the
2222 - .. parsed-literal::
2224 the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*)
2226 This error is generated if you try to assign an attribute with a value
2227 of a type that cannot be converted to the attribute's type.
2230 - .. parsed-literal::
2232 *class-name()* threw an exception, *class-name:function-name()* threw an exception
2234 The class' constructor or member function threw an unknown exception.
2235 Known exceptions are const char*, std::exception. See the
2236 `exceptions`_ section.
2238 - .. parsed-literal::
2240 no overload of '*class-name:function-name*' matched the arguments (*parameter-types*)
2241 no match for function call '*function-name*' with the parameters (*parameter-types*)
2242 no constructor of *class-name* matched the arguments (*parameter-types*)
2243 no operator *operator-name* matched the arguments (*parameter-types*)
2245 No function/operator with the given name takes the parameters you gave
2246 it. You have either misspelled the function name, or given it incorrect
2247 parameters. This error is followed by a list of possible candidate
2248 functions to help you figure out what parameter has the wrong type. If
2249 the candidate list is empty there's no function at all with that name.
2250 See the signature matching section.
2252 - .. parsed-literal::
2254 call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous
2255 ambiguous match for function call '*function-name*' with the parameters (*parameter-types*)
2256 call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous
2257 call of overloaded operator *operator-name* (*parameter-types*) is ambiguous
2259 This means that the function/operator you are trying to call has at least
2260 one other overload that matches the arguments just as good as the first
2263 - .. parsed-literal::
2265 cannot derive from C++ class '*class-name*'. It does not have a wrapped type.
2271 What's up with __cdecl and __stdcall?
2272 If you're having problem with functions
2273 that cannot be converted from ``void (__stdcall *)(int,int)`` to
2274 ``void (__cdecl*)(int,int)``. You can change the project settings to make the
2275 compiler generate functions with __cdecl calling conventions. This is
2276 a problem in developer studio.
2278 What's wrong with functions taking variable number of arguments?
2279 You cannot register a function with ellipses in its signature. Since
2280 ellipses don't preserve type safety, those should be avoided anyway.
2282 Internal structure overflow in VC
2283 If you, in visual studio, get fatal error C1204: compiler limit :
2284 internal structure overflow. You should try to split that compilation
2285 unit up in smaller ones.
2287 .. the three entries above were removed, why?
2289 What's wrong with precompiled headers in VC?
2290 Visual Studio doesn't like anonymous namespaces in its precompiled
2291 headers. If you encounter this problem you can disable precompiled
2292 headers for the compilation unit (cpp-file) that uses luabind.
2294 error C1076: compiler limit - internal heap limit reached in VC
2295 In visual studio you will probably hit this error. To fix it you have to
2296 increase the internal heap with a command-line option. We managed to
2297 compile the test suit with /Zm300, but you may need a larger heap then
2300 error C1055: compiler limit \: out of keys in VC
2301 It seems that this error occurs when too many assert() are used in a
2302 program, or more specifically, the __LINE__ macro. It seems to be fixed by
2303 changing /ZI (Program database for edit and continue) to /Zi
2306 How come my executable is huge?
2307 If you're compiling in debug mode, you will probably have a lot of
2308 debug-info and symbols (luabind consists of a lot of functions). Also,
2309 if built in debug mode, no optimizations were applied, luabind relies on
2310 that the compiler is able to inline functions. If you built in release
2311 mode, try running strip on your executable to remove export-symbols,
2312 this will trim down the size.
2314 Our tests suggests that cygwin's gcc produces much bigger executables
2315 compared to gcc on other platforms and other compilers.
2317 .. HUH?! // check the magic number that identifies luabind's functions
2319 Can I register class templates with luabind?
2320 Yes you can, but you can only register explicit instantiations of the
2321 class. Because there's no Lua counterpart to C++ templates. For example,
2322 you can register an explicit instantiation of std::vector<> like this::
2326 class_<std::vector<int> >("vector")
2327 .def(constructor<int>)
2328 .def("push_back", &std::vector<int>::push_back)
2331 .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
2333 Do I have to register destructors for my classes?
2334 No, the destructor of a class is always called by luabind when an
2335 object is collected. Note that Lua has to own the object to collect it.
2336 If you pass it to C++ and gives up ownership (with adopt policy) it will
2337 no longer be owned by Lua, and not collected.
2339 If you have a class hierarchy, you should make the destructor virtual if
2340 you want to be sure that the correct destructor is called (this apply to C++
2343 .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ.
2345 Fatal Error C1063 compiler limit \: compiler stack overflow in VC
2346 VC6.5 chokes on warnings, if you are getting alot of warnings from your
2347 code try suppressing them with a pragma directive, this should solve the
2350 Crashes when linking against luabind as a dll in windows
2351 When you build luabind, Lua and you project, make sure you link against
2352 the runtime dynamically (as a dll).
2354 I cannot register a function with a non-const parameter
2355 This is because there is no way to get a reference to a Lua value. Have
2356 a look at out_value and pure_out_value policies.
2362 - You cannot use strings with extra nulls in them as member names that refers
2365 - If one class registers two functions with the same name and the same
2366 signature, there's currently no error. The last registered function will
2367 be the one that's used.
2369 - In VC7, classes can not be called test.
2371 - If you register a function and later rename it, error messages will use the
2372 original function name.
2374 - luabind does not support class hierarchies with virtual inheritance. Casts are
2375 done with static pointer offsets.
2377 .. remove? - Visual studio have problems selecting the correct overload of std::swap()
2378 for luabind::object.
2384 Written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
2385 All rights reserved.
2387 Evan Wies has contributed with thorough testing, countless bug reports
2390 This library was highly inspired by Dave Abrahams' Boost.Python_ library.
2392 .. _Boost.Python: http://www.boost.org/libraries/python