1 .. include:: version.rst
7 :Author: Daniel Wallin, Arvid Norberg
8 :Copyright: Copyright Daniel Wallin, Arvid Norberg 2003.
9 :License: Permission is hereby granted, free of charge, to any person obtaining a
10 copy of this software and associated documentation files (the "Software"),
11 to deal in the Software without restriction, including without limitation
12 the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 and/or sell copies of the Software, and to permit persons to whom the
14 Software is furnished to do so, subject to the following conditions:
16 The above copyright notice and this permission notice shall be included
17 in all copies or substantial portions of the Software.
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20 ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22 PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23 SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
24 ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
27 OR OTHER DEALINGS IN THE SOFTWARE.
30 .. _MIT license: http://www.opensource.org/licenses/mit-license.php
31 .. _Boost: http://www.boost.org
33 Note: This library is currently in public beta phase. This documentation
34 should be considered beta as well. Please report any grammatical
35 corrections/spelling corrections.
40 .. section-numbering::
42 .. |...| unicode:: U+02026
47 Luabind is a library that helps you create bindings between C++ and Lua. It has
48 the ability to expose functions and classes, written in C++, to Lua. It will
49 also supply the functionality to define classes in Lua and let them derive from
50 other Lua classes or C++ classes. Lua classes can override virtual functions
51 from their C++ base classes. It is written towards Lua 5.0, and does not work
54 It is implemented utilizing template meta programming. That means that you
55 don't need an extra preprocess pass to compile your project (it is done by the
56 compiler). It also means you don't (usually) have to know the exact signature
57 of each function you register, since the library will generate code depending
58 on the compile-time type of the function (which includes the signature). The
59 main drawback of this approach is that the compilation time will increase for
60 the file that does the registration, it is therefore recommended that you
61 register everything in the same cpp-file.
63 Luabind is released under the terms of the `MIT license`_.
65 We are very interested in hearing about projects that use luabind, please let
66 us know about your project.
68 The main channel for help and feedback is the `luabind mailing list`_.
69 There's also an IRC channel ``#luabind`` on irc.freenode.net.
71 .. _`luabind mailing list`: https://lists.sourceforge.net/lists/listinfo/luabind-user
79 - Overloaded free functions
81 - Overloaded member functions
85 - Lua functions in C++
87 - Lua classes (single inheritance)
88 - Derives from Lua or C++ classes
89 - Override virtual functions from C++ classes
90 - Implicit casts between registered types
91 - Best match signature matching
92 - Return value policies and parameter policies
98 Luabind has been tested to work on the following compilers:
102 - Visual Studio 6.0 (sp 5)
103 - Intel C++ 6.0 (Windows)
104 - GCC 2.95.3 (cygwin)
105 - GCC 3.0.4 (Debian/Linux)
106 - GCC 3.1 (SunOS 5.8)
109 - GCC 3.3 (Apple, MacOS X)
110 - GCC 4.0 (Apple, MacOS X)
112 It has been confirmed not to work with:
114 - GCC 2.95.2 (SunOS 5.8)
116 Metrowerks 8.3 (Windows) compiles but fails the const-test. This
117 means that const member functions are treated as non-const member
120 If you have tried luabind with a compiler not listed here, let us know
123 .. include:: building.rst
128 To use luabind, you must include ``lua.h`` and luabind's main header file::
135 #include <luabind/luabind.hpp>
137 This includes support for both registering classes and functions. If you just
138 want to have support for functions or classes you can include
139 ``luabind/function.hpp`` and ``luabind/class.hpp`` separately::
141 #include <luabind/function.hpp>
142 #include <luabind/class.hpp>
144 The first thing you need to do is to call ``luabind::open(lua_State*)`` which
145 will register the functions to create classes from Lua, and initialize some
146 state-global structures used by luabind. If you don't call this function you
147 will hit asserts later in the library. There is no corresponding close function
148 because once a class has been registered in Lua, there really isn't any good
149 way to remove it. Partly because any remaining instances of that class relies
150 on the class being there. Everything will be cleaned up when the state is
153 .. Isn't this wrong? Don't we include lua.h using lua_include.hpp ?
155 Luabind's headers will never include ``lua.h`` directly, but through
156 ``<luabind/lua_include.hpp>``. If you for some reason need to include another
157 Lua header, you can modify this file.
166 #include <luabind/luabind.hpp>
170 std::cout << "hello world!\n";
173 extern "C" int init(lua_State* L)
175 using namespace luabind;
189 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
190 > loadlib('hello_world.dll', 'init')()
198 Everything that gets registered in Lua is registered in a namespace (Lua
199 tables) or in the global scope (called module). All registrations must be
200 surrounded by its scope. To define a module, the ``luabind::module`` class is
201 used. It is used like this::
208 This will register all declared functions or classes in the global namespace in
209 Lua. If you want to have a namespace for your module (like the standard
210 libraries) you can give a name to the constructor, like this::
212 module(L, "my_library")
217 Here all declarations will be put in the my_library table.
219 If you want nested namespace's you can use the ``luabind::namespace_`` class. It
220 works exactly as ``luabind::module`` except that it doesn't take a lua_State*
221 in it's constructor. An example of its usage could look like this::
223 module(L, "my_library")
229 // library-private declarations
233 As you might have figured out, the following declarations are equivalent::
237 namespace_("my_library")
246 module(L, "my_library")
251 Each declaration must be separated by a comma, like this::
258 .def(constructor<int, int>),
263 More about the actual declarations in the `Binding functions to Lua`_ and
264 `Binding classes to Lua`_ sections.
266 A word of caution, if you are in really bad need for performance, putting your
267 functions in tables will increase the lookup time.
270 Binding functions to Lua
271 ========================
273 To bind functions to Lua you use the function ``luabind::def()``. It has the
276 template<class F, class policies>
277 void def(const char* name, F f, const Policies&);
279 - name is the name the function will have within Lua.
280 - F is the function pointer you want to register.
281 - The Policies parameter is used to describe how parameters and return values
282 are treated by the function, this is an optional parameter. More on this in
283 the `policies`_ section.
285 An example usage could be if you want to register the function ``float
290 def("sin", &std::sin)
296 If you have more than one function with the same name, and want to register
297 them in Lua, you have to explicitly give the signature. This is to let C++ know
298 which function you refer to. For example, if you have two functions, ``int
299 f(const char*)`` and ``void f(int)``. ::
303 def("f", (int(*)(const char*)) &f),
304 def("f", (void(*)(int)) &f)
310 luabind will generate code that checks the Lua stack to see if the values there
311 can match your functions' signatures. It will handle implicit typecasts between
312 derived classes, and it will prefer matches with the least number of implicit
313 casts. In a function call, if the function is overloaded and there's no
314 overload that match the parameters better than the other, you have an
315 ambiguity. This will spawn a run-time error, stating that the function call is
316 ambiguous. A simple example of this is to register one function that takes an
317 int and one that takes a float. Since Lua doesn't distinguish between floats and
318 integers, both will always match.
320 Since all overloads are tested, it will always find the best match (not the
321 first match). This also means that it can handle situations where the only
322 difference in the signature is that one member function is const and the other
325 .. sidebar:: Ownership transfer
327 To correctly handle ownership transfer, create_a() would need an adopt
328 return value policy. More on this in the `Policies`_ section.
330 For example, if the following function and class is registered:
348 And the following Lua code is executed::
351 a1:f() -- the const version is called
354 a2:f() -- the non-const version is called
365 Calling Lua functions
366 ---------------------
368 To call a Lua function, you can either use ``call_function()`` or
374 Ret call_function(lua_State* L, const char* name, ...)
376 Ret call_function(object const& obj, ...)
378 There are two overloads of the ``call_function`` function, one that calls
379 a function given its name, and one that takes an object that should be a Lua
380 value that can be called as a function.
382 The overload that takes a name can only call global Lua functions. The ...
383 represents a variable number of parameters that are sent to the Lua
384 function. This function call may throw ``luabind::error`` if the function
387 The return value isn't actually Ret (the template parameter), but a proxy
388 object that will do the function call. This enables you to give policies to the
389 call. You do this with the operator[]. You give the policies within the
390 brackets, like this::
392 int ret = call_function<int>(
395 , new complex_class()
398 If you want to pass a parameter as a reference, you have to wrap it with the
401 __ http://www.boost.org/doc/html/ref.html
405 int ret = call_function(L, "fun", boost::ref(val));
408 If you want to use a custom error handler for the function call, see
409 ``set_pcall_callback`` under `pcall errorfunc`_.
414 To start a Lua thread, you have to call ``lua_resume()``, this means that you
415 cannot use the previous function ``call_function()`` to start a thread. You have
421 Ret resume_function(lua_State* L, const char* name, ...)
423 Ret resume_function(object const& obj, ...)
430 Ret resume(lua_State* L, ...)
432 The first time you start the thread, you have to give it a function to execute. i.e. you
433 have to use ``resume_function``, when the Lua function yields, it will return the first
434 value passed in to ``lua_yield()``. When you want to continue the execution, you just call
435 ``resume()`` on your ``lua_State``, since it's already executing a function, you don't pass
436 it one. The parameters to ``resume()`` will be returned by ``yield()`` on the Lua side.
438 For yielding C++-functions (without the support of passing data back and forth between the
439 Lua side and the c++ side), you can use the yield_ policy.
441 With the overload of ``resume_function`` that takes an object_, it is important that the
442 object was constructed with the thread as its ``lua_State*``. Like this:
446 lua_State* thread = lua_newthread(L);
447 object fun = get_global(**thread**)["my_thread_fun"];
448 resume_function(fun);
451 Binding classes to Lua
452 ======================
454 To register classes you use a class called ``class_``. Its name is supposed to
455 resemble the C++ keyword, to make it look more intuitive. It has an overloaded
456 member function ``def()`` that is used to register member functions, operators,
457 constructors, enums and properties on the class. It will return its
458 this-pointer, to let you register more members directly.
460 Let's start with a simple example. Consider the following C++ class::
465 testclass(const std::string& s): m_string(s) {}
466 void print_string() { std::cout << m_string << "\n"; }
469 std::string m_string;
472 To register it with a Lua environment, write as follows (assuming you are using
477 class_<testclass>("testclass")
478 .def(constructor<const std::string&>())
479 .def("print_string", &testclass::print_string)
482 This will register the class with the name testclass and constructor that takes
483 a string as argument and one member function with the name ``print_string``.
487 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
488 > a = testclass('a string')
492 It is also possible to register free functions as member functions. The
493 requirement on the function is that it takes a pointer, const pointer,
494 reference or const reference to the class type as the first parameter. The rest
495 of the parameters are the ones that are visible in Lua, while the object
496 pointer is given as the first parameter. If we have the following C++ code::
503 int plus(A* o, int v) { return o->a + v; }
505 You can register ``plus()`` as if it was a member function of A like this::
510 ``plus()`` can now be called as a member function on A with one parameter, int.
511 If the object pointer parameter is const, the function will act as if it was a
512 const member function (it can be called on const objects).
515 Overloaded member functions
516 ---------------------------
518 When binding more than one overloads of a member function, or just binding
519 one overload of an overloaded member function, you have to disambiguate
520 the member function pointer you pass to ``def``. To do this, you can use an
521 ordinary C-style cast, to cast it to the right overload. To do this, you have
522 to know how to express member function types in C++, here's a short tutorial
523 (for more info, refer to your favourite book on C++).
525 The syntax for member function pointer follows:
529 *return-value* (*class-name*::\*)(*arg1-type*, *arg2-type*, *...*)
531 Here's an example illlustrating this::
542 .def("f", (void(A::*)(int))&A::f)
544 This selects the first overload of the function ``f`` to bind. The second
545 overload is not bound.
551 To register a global data member with a class is easily done. Consider the
559 This class is registered like this::
564 .def_readwrite("a", &A::a)
567 This gives read and write access to the member variable ``A::a``. It is also
568 possible to register attributes with read-only access::
573 .def_readonly("a", &A::a)
576 When binding members that are a non-primitive type, the auto generated getter
577 function will return a reference to it. This is to allow chained .-operators.
578 For example, when having a struct containing another struct. Like this::
583 When binding ``B`` to lua, the following expression code should work::
589 This requires the first lookup (on ``a``) to return a reference to ``A``, and
590 not a copy. In that case, luabind will automatically use the dependency policy
591 to make the return value dependent on the object in which it is stored. So, if
592 the returned reference lives longer than all references to the object (b in
593 this case) it will keep the object alive, to avoid being a dangling pointer.
595 You can also register getter and setter functions and make them look as if they
596 were a public data member. Consider the following class::
601 void set_a(int x) { a = x; }
602 int get_a() const { return a; }
608 It can be registered as if it had a public data member a like this::
611 .property("a", &A::get_a, &A::set_a)
613 This way the ``get_a()`` and ``set_a()`` functions will be called instead of
614 just writing to the data member. If you want to make it read only you can just
615 omit the last parameter. Please note that the get function **has to be
616 const**, otherwise it won't compile. This seems to be a common source of errors.
622 If your class contains enumerated constants (enums), you can register them as
623 well to make them available in Lua. Note that they will not be type safe, all
624 enums are integers in Lua, and all functions that takes an enum, will accept
625 any integer. You register them like this::
633 value("my_2nd_enum", 7),
634 value("another_enum", 6)
638 In Lua they are accessed like any data member, except that they are read-only
639 and reached on the class itself rather than on an instance of the class.
643 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
646 > print(A.another_enum)
653 To bind operators you have to include ``<luabind/operator.hpp>``.
655 The mechanism for registering operators on your class is pretty simple. You use
656 a global name ``luabind::self`` to refer to the class itself and then you just
657 write the operator expression inside the ``def()`` call. This class::
661 vec operator+(int s);
664 Is registered like this:
671 .def(**self + int()**)
674 This will work regardless if your plus operator is defined inside your class or
677 If your operator is const (or, when defined as a free function, takes a const
678 reference to the class itself) you have to use ``const_self`` instead of
686 .def(**const_self** + int())
689 The operators supported are those available in Lua:
695 This means, no in-place operators. The equality operator (``==``) has a little
696 hitch; it will not be called if the references are equal. This means that the
697 ``==`` operator has to do pretty much what's it's expected to do.
699 Lua does not support operators such as ``!=``, ``>`` or ``>=``. That's why you
700 can only register the operators listed above. When you invoke one of the
701 mentioned operators, lua will define it in terms of one of the avaliable
704 In the above example the other operand type is instantiated by writing
705 ``int()``. If the operand type is a complex type that cannot easily be
706 instantiated you can wrap the type in a class called ``other<>``. For example:
708 To register this class, we don't want to instantiate a string just to register
715 vec operator+(std::string);
718 Instead we use the ``other<>`` wrapper like this:
725 .def(self + **other<std::string>()**)
728 To register an application (function call-) operator:
735 .def( **self(int())** )
738 There's one special operator. In Lua it's called ``__tostring``, it's not
739 really an operator. It is used for converting objects to strings in a standard
740 way in Lua. If you register this functionality, you will be able to use the lua
741 standard function ``tostring()`` for converting your object to a string.
743 To implement this operator in C++ you should supply an ``operator<<`` for
744 std::ostream. Like this example:
749 std::ostream& operator<<(std::ostream&, number&);
755 class_<number>("number")
756 .def(**tostring(self)**)
760 Nested scopes and static functions
761 ----------------------------------
763 It is possible to add nested scopes to a class. This is useful when you need
764 to wrap a nested class, or a static function.
769 .def(constructor<>())
772 class_<inner>("nested"),
776 In this example, ``f`` will behave like a static member function of the class
777 ``foo``, and the class ``nested`` will behave like a nested class of ``foo``.
779 It's also possible to add namespace's to classes using the same syntax.
785 If you want to register classes that derives from other classes, you can
786 specify a template parameter ``bases<>`` to the ``class_`` instantiation. The
787 following hierarchy::
792 Would be registered like this::
800 If you have multiple inheritance you can specify more than one base. If B would
801 also derive from a class C, it would be registered like this::
805 class_<B, bases<A, C> >("B")
808 Note that you can omit ``bases<>`` when using single inheritance.
811 If you don't specify that classes derive from each other, luabind will not
812 be able to implicitly cast pointers between the types.
818 When registering a class you can tell luabind to hold all instances
819 explicitly created in Lua in a specific smart pointer type, rather than
820 the default raw pointer. This is done by passing an additional template
821 parameter to ``class_``:
827 Where the requirements of ``P`` are:
829 ======================== =======================================
831 ======================== =======================================
833 ``get_pointer(p)`` Convertible to ``X*``
834 ======================== =======================================
838 * ``raw`` is of type ``X*``
839 * ``p`` is an instance of ``P``
841 ``get_pointer()`` overloads are provided for the smart pointers in
842 Boost, and ``std::auto_ptr<>``. Should you need to provide your own
843 overload, note that it is called unqualified and is expected to be found
844 by *argument dependent lookup*. Thus it should be defined in the same
845 namespace as the pointer type it operates on.
851 class_<X, **boost::scoped_ptr<X>** >("X")
852 .def(constructor<>())
854 Will cause luabind to hold any instance created on the Lua side in a
855 ``boost::scoped_ptr<X>``.
859 ``get_const_holder()`` has been removed. Automatic conversions
860 between ``smart_ptr<X>`` and ``smart_ptr<X const>`` no longer work.
864 ``__ok`` has been removed. Similar functionality can be implemented
865 for specific pointer types by doing something along the lines of:
869 bool is_non_null(std::auto_ptr<X> const& p)
876 def("is_non_null", &is_non_null)
878 When registering a hierarchy of classes, where all instances are to be held
879 by a smart pointer, all the classes should have the baseclass' holder type.
886 class_<base, boost::shared_ptr<base> >("base")
887 .def(constructor<>()),
888 class_<derived, base, **boost::shared_ptr<base>** >("base")
889 .def(constructor<>())
892 Internally, luabind will do the necessary conversions on the raw pointers, which
893 are first extracted from the holder type.
896 Splitting class registrations
897 -----------------------------
899 In some situations it may be desirable to split a registration of a class
900 across different compilation units. Partly to save rebuild time when changing
901 in one part of the binding, and in some cases compiler limits may force you
902 to split it. To do this is very simple. Consider the following sample code::
904 void register_part1(class_<X>& x)
909 void register_part2(class_<X>& x)
914 void register_(lua_State* L)
924 Here, the class ``X`` is registered in two steps. The two functions
925 ``register_part1`` and ``register_part2`` may be put in separate compilation
928 To separate the module registration and the classes to be registered, see
929 `Splitting up the registration`_.
932 Adding converters for user defined types
933 ========================================
935 It is possible to get luabind to handle user defined types like it does
936 the built in types by specializing ``luabind::default_converter<>``:
942 int_wrapper(int value)
952 struct default_converter<X>
953 : native_converter_base<X>
955 static int compute_score(lua_State* L, int index)
957 return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;
960 X from(lua_State* L, int index)
962 return X(lua_tonumber(L, index));
965 void to(lua_State* L, X const& x)
967 lua_pushnumber(L, x.value);
972 struct default_converter<X const&>
973 : default_converter<X>
977 Note that ``default_converter<>`` is instantiated for the actual argument and
978 return types of the bound functions. In the above example, we add a
979 specialization for ``X const&`` that simply forwards to the ``X`` converter.
980 This lets us export functions which accept ``X`` by const reference.
982 ``native_converter_base<>`` should be used as the base class for the
983 specialized converters. It simplifies the converter interface, and
984 provides a mean for backward compatibility since the underlying
985 interface is in flux.
988 Binding function objects with explicit signatures
989 =================================================
991 Using ``luabind::tag_function<>`` it is possible to export function objects
992 from which luabind can't automatically deduce a signature. This can be used to
993 slightly alter the signature of a bound function, or even to bind stateful
1000 template <class Signature, class F>
1001 *implementation-defined* tag_function(F f);
1003 Where ``Signature`` is a function type describing the signature of ``F``.
1004 It can be used like this::
1008 // alter the signature so that the return value is ignored
1009 def("f", tag_function<void(int)>(f));
1017 int operator()(int y) const
1023 // bind a stateful function object
1024 def("plus3", tag_function<int(int)>(plus(3)));
1030 Since functions have to be able to take Lua values (of variable type) we need a
1031 wrapper around them. This wrapper is called ``luabind::object``. If the
1032 function you register takes an object, it will match any Lua value. To use it,
1033 you need to include ``<luabind/object.hpp>``.
1043 object(lua_State\*, T const& value);
1044 object(from_stack const&);
1045 object(object const&);
1050 lua_State\* interpreter() const;
1052 bool is_valid() const;
1053 operator *safe_bool_type* () const;
1056 *implementation-defined* operator[](Key const&);
1059 object& operator=(T const&);
1060 object& operator=(object const&);
1062 bool operator==(object const&) const;
1063 bool operator<(object const&) const;
1064 bool operator<=(object const&) const;
1065 bool operator>(object const&) const;
1066 bool operator>=(object const&) const;
1067 bool operator!=(object const&) const;
1070 *implementation-defined* operator[](T const& key) const
1074 *implementation-defined* operator()();
1077 *implementation-defined* operator()(A0 const& a0);
1079 template<class A0, class A1>
1080 *implementation-defined* operator()(A0 const& a0, A1 const& a1);
1085 When you have a Lua object, you can assign it a new value with the assignment
1086 operator (=). When you do this, the ``default_policy`` will be used to make the
1087 conversion from C++ value to Lua. If your ``luabind::object`` is a table you
1088 can access its members through the operator[] or the Iterators_. The value
1089 returned from the operator[] is a proxy object that can be used both for
1090 reading and writing values into the table (using operator=).
1092 Note that it is impossible to know if a Lua value is indexable or not
1093 (``lua_gettable`` doesn't fail, it succeeds or crashes). This means that if
1094 you're trying to index something that cannot be indexed, you're on your own.
1095 Lua will call its ``panic()`` function. See `lua panic`_.
1097 There are also free functions that can be used for indexing the table, see
1098 `Related functions`_.
1100 The constructor that takes a ``from_stack`` object is used when you want to
1101 initialize the object with a value from the lua stack. The ``from_stack``
1102 type has the following constructor::
1104 from_stack(lua_State* L, int index);
1106 The index is an ordinary lua stack index, negative values are indexed from the
1107 top of the stack. You use it like this::
1109 object o(from_stack(L, -1));
1111 This will create the object ``o`` and copy the value from the top of the lua stack.
1113 The ``interpreter()`` function returns the Lua state where this object is stored.
1114 If you want to manipulate the object with Lua functions directly you can push
1115 it onto the Lua stack by calling ``push()``.
1117 The operator== will call lua_equal() on the operands and return its result.
1119 The ``is_valid()`` function tells you whether the object has been initialized
1120 or not. When created with its default constructor, objects are invalid. To make
1121 an object valid, you can assign it a value. If you want to invalidate an object
1122 you can simply assign it an invalid object.
1124 The ``operator safe_bool_type()`` is equivalent to ``is_valid()``. This means
1125 that these snippets are equivalent::
1143 The application operator will call the value as if it was a function. You can
1144 give it any number of parameters (currently the ``default_policy`` will be used
1145 for the conversion). The returned object refers to the return value (currently
1146 only one return value is supported). This operator may throw ``luabind::error``
1147 if the function call fails. If you want to specify policies to your function
1148 call, you can use index-operator (operator[]) on the function call, and give
1149 the policies within the [ and ]. Like this::
1154 , new my_complex_structure(6)
1157 This tells luabind to make Lua adopt the ownership and responsibility for the
1158 pointer passed in to the lua-function.
1160 It's important that all instances of object have been destructed by the time
1161 the Lua state is closed. The object will keep a pointer to the lua state and
1162 release its Lua object in its destructor.
1164 Here's an example of how a function can use a table::
1166 void my_function(object const& table)
1168 if (type(table) == LUA_TTABLE)
1170 table["time"] = std::clock();
1171 table["name"] = std::rand() < 500 ? "unusual" : "usual";
1173 std::cout << object_cast<std::string>(table[5]) << "\n";
1177 If you take a ``luabind::object`` as a parameter to a function, any Lua value
1178 will match that parameter. That's why we have to make sure it's a table before
1183 std::ostream& operator<<(std::ostream&, object const&);
1185 There's a stream operator that makes it possible to print objects or use
1186 ``boost::lexical_cast`` to convert it to a string. This will use lua's string
1187 conversion function. So if you convert a C++ object with a ``tostring``
1188 operator, the stream operator for that type will be used.
1193 There are two kinds of iterators. The normal iterator that will use the metamethod
1194 of the object (if there is any) when the value is retrieved. This iterator is simply
1195 called ``luabind::iterator``. The other iterator is called ``luabind::raw_iterator``
1196 and will bypass the metamethod and give the true contents of the table. They have
1197 identical interfaces, which implements the ForwardIterator_ concept. Apart from
1198 the members of standard iterators, they have the following members and constructors:
1200 .. _ForwardIterator: http://www.sgi.com/tech/stl/ForwardIterator.html
1207 iterator(object const&);
1211 *standard iterator members*
1214 The constructor that takes a ``luabind::object`` is actually a template that can be
1215 used with object. Passing an object as the parameter to the iterator will
1216 construct the iterator to refer to the first element in the object.
1218 The default constructor will initialize the iterator to the one-past-end
1219 iterator. This is used to test for the end of the sequence.
1221 The value type of the iterator is an implementation defined proxy type which
1222 supports the same operations as ``luabind::object``. Which means that in most
1223 cases you can just treat it as an ordinary object. The difference is that any
1224 assignments to this proxy will result in the value being inserted at the
1225 iterators position, in the table.
1227 The ``key()`` member returns the key used by the iterator when indexing the
1228 associated Lua table.
1230 An example using iterators::
1232 for (iterator i(globals(L)["a"]), end; i != end; ++i)
1237 The iterator named ``end`` will be constructed using the default constructor
1238 and hence refer to the end of the sequence. This example will simply iterate
1239 over the entries in the global table ``a`` and set all its values to 1.
1244 There are a couple of functions related to objects and tables.
1248 int type(object const&);
1250 This function will return the lua type index of the given object.
1251 i.e. ``LUA_TNIL``, ``LUA_TNUMBER`` etc.
1255 template<class T, class K>
1256 void settable(object const& o, K const& key, T const& value);
1258 object gettable(object const& o, K const& key);
1259 template<class T, class K>
1260 void rawset(object const& o, K const& key, T const& value);
1262 object rawget(object const& o, K const& key);
1264 These functions are used for indexing into tables. ``settable`` and ``gettable``
1265 translates into calls to ``lua_settable`` and ``lua_gettable`` respectively. Which
1266 means that you could just as well use the index operator of the object.
1268 ``rawset`` and ``rawget`` will translate into calls to ``lua_rawset`` and
1269 ``lua_rawget`` respectively. So they will bypass any metamethod and give you the
1270 true value of the table entry.
1275 T object_cast<T>(object const&);
1276 template<class T, class Policies>
1277 T object_cast<T>(object const&, Policies);
1280 boost::optional<T> object_cast_nothrow<T>(object const&);
1281 template<class T, class Policies>
1282 boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
1284 The ``object_cast`` function casts the value of an object to a C++ value.
1285 You can supply a policy to handle the conversion from lua to C++. If the cast
1286 cannot be made a ``cast_failed`` exception will be thrown. If you have
1287 defined LUABIND_NO_ERROR_CHECKING (see `Build options`_) no checking will occur,
1288 and if the cast is invalid the application may very well crash. The nothrow
1289 versions will return an uninitialized ``boost::optional<T>`` object, to
1290 indicate that the cast could not be performed.
1292 The function signatures of all of the above functions are really templates
1293 for the object parameter, but the intention is that you should only pass
1294 objects in there, that's why it's left out of the documentation.
1298 object globals(lua_State*);
1299 object registry(lua_State*);
1301 These functions return the global environment table and the registry table respectively.
1305 object newtable(lua_State*);
1307 This function creates a new table and returns it as an object.
1311 object getmetatable(object const& obj);
1312 void setmetatable(object const& obj, object const& metatable);
1314 These functions get and set the metatable of a Lua object.
1318 lua_CFunction tocfunction(object const& value);
1319 template <class T> T* touserdata(object const& value)
1321 These extract values from the object at a lower level than ``object_cast()``.
1325 object getupvalue(object const& function, int index);
1326 void setupvalue(object const& function, int index, object const& value);
1328 These get and set the upvalues of ``function``.
1333 To set a table entry to ``nil``, you can use ``luabind::nil``. It will avoid
1334 having to take the detour by first assigning ``nil`` to an object and then
1335 assign that to the table entry. It will simply result in a ``lua_pushnil()``
1336 call, instead of copying an object.
1341 object table = newtable(L);
1342 table["foo"] = "bar";
1344 // now, clear the "foo"-field
1348 Defining classes in Lua
1349 =======================
1351 In addition to binding C++ functions and classes with Lua, luabind also provide
1352 an OO-system in Lua. ::
1354 class 'lua_testclass'
1356 function lua_testclass:__init(name)
1360 function lua_testclass:print()
1364 a = lua_testclass('example')
1368 Inheritance can be used between lua-classes::
1370 class 'derived' (lua_testclass)
1372 function derived:__init()
1373 lua_testclass.__init(self, 'derived name')
1376 function derived:print()
1377 print('Derived:print() -> ')
1378 lua_testclass.print(self)
1381 The base class is initialized explicitly by calling its ``__init()``
1384 As you can see in this example, you can call the base class member functions.
1385 You can find all member functions in the base class, but you will have to give
1386 the this-pointer (``self``) as first argument.
1392 It is also possible to derive Lua classes from C++ classes, and override
1393 virtual functions with Lua functions. To do this we have to create a wrapper
1394 class for our C++ base class. This is the class that will hold the Lua object
1395 when we instantiate a Lua class.
1403 { std::cout << s << "\n"; }
1405 virtual void f(int a)
1406 { std::cout << "f(" << a << ")\n"; }
1409 struct base_wrapper : base, luabind::wrap_base
1411 base_wrapper(const char* s)
1415 virtual void f(int a)
1420 static void default_f(base* ptr, int a)
1422 return ptr->base::f(a);
1430 class_<base, base_wrapper>("base")
1431 .def(constructor<const char*>())
1432 .def("f", &base::f, &base_wrapper::default_f)
1436 Since MSVC6.5 doesn't support explicit template parameters
1437 to member functions, instead of using the member function ``call()``
1438 you call a free function ``call_member()`` and pass the this-pointer
1441 Note that if you have both base classes and a base class wrapper, you must give
1442 both bases and the base class wrapper type as template parameter to
1443 ``class_`` (as done in the example above). The order in which you specify
1444 them is not important. You must also register both the static version and the
1445 virtual version of the function from the wrapper, this is necessary in order
1446 to allow luabind to use both dynamic and static dispatch when calling the function.
1449 It is extremely important that the signatures of the static (default) function
1450 is identical to the virtual function. The fact that one of them is a free
1451 function and the other a member function doesn't matter, but the parameters
1452 as seen from lua must match. It would not have worked if the static function
1453 took a ``base_wrapper*`` as its first argument, since the virtual function
1454 takes a ``base*`` as its first argument (its this pointer). There's currently
1455 no check in luabind to make sure the signatures match.
1457 If we didn't have a class wrapper, it would not be possible to pass a Lua class
1458 back to C++. Since the entry points of the virtual functions would still point
1459 to the C++ base class, and not to the functions defined in Lua. That's why we
1460 need one function that calls the base class' real function (used if the lua
1461 class doesn't redefine it) and one virtual function that dispatches the call
1462 into luabind, to allow it to select if a Lua function should be called, or if
1463 the original function should be called. If you don't intend to derive from a
1464 C++ class, or if it doesn't have any virtual member functions, you can register
1465 it without a class wrapper.
1467 You don't need to have a class wrapper in order to derive from a class, but if
1468 it has virtual functions you may have silent errors.
1470 .. Unnecessary? The rule of thumb is:
1471 If your class has virtual functions, create a wrapper type, if it doesn't
1472 don't create a wrapper type.
1474 The wrappers must derive from ``luabind::wrap_base``, it contains a Lua reference
1475 that will hold the Lua instance of the object to make it possible to dispatch
1476 virtual function calls into Lua. This is done through an overloaded member function::
1479 Ret call(char const* name, ...)
1481 Its used in a similar way as ``call_function``, with the exception that it doesn't
1482 take a ``lua_State`` pointer, and the name is a member function in the Lua class.
1486 The current implementation of ``call_member`` is not able to distinguish const
1487 member functions from non-const. If you have a situation where you have an overloaded
1488 virtual function where the only difference in their signatures is their constness, the
1489 wrong overload will be called by ``call_member``. This is rarely the case though.
1494 When a pointer or reference to a registered class with a wrapper is passed
1495 to Lua, luabind will query for it's dynamic type. If the dynamic type
1496 inherits from ``wrap_base``, object identity is preserved.
1501 struct A_wrap : A, wrap_base { .. };
1503 A* f(A* ptr) { return ptr; }
1507 class_<A, A_wrap>("A"),
1515 > assert(x == f(x)) -- object identity is preserved when object is
1516 -- passed through C++
1518 This functionality relies on RTTI being enabled (that ``LUABIND_NO_RTTI`` is
1521 Overloading operators
1522 ---------------------
1524 You can overload most operators in Lua for your classes. You do this by simply
1525 declaring a member function with the same name as an operator (the name of the
1526 metamethods in Lua). The operators you can overload are:
1541 ``__tostring`` isn't really an operator, but it's the metamethod that is called
1542 by the standard library's ``tostring()`` function. There's one strange behavior
1543 regarding binary operators. You are not guaranteed that the self pointer you
1544 get actually refers to an instance of your class. This is because Lua doesn't
1545 distinguish the two cases where you get the other operand as left hand value or
1546 right hand value. Consider the following examples::
1550 function my_class:__init(v)
1554 function my_class:__sub(v)
1555 return my_class(self.val - v.val)
1558 function my_class:__tostring()
1562 This will work well as long as you only subtracts instances of my_class with
1563 each other. But If you want to be able to subtract ordinary numbers from your
1564 class too, you have to manually check the type of both operands, including the
1567 function my_class:__sub(v)
1568 if (type(self) == 'number') then
1569 return my_class(self - v.val)
1571 elseif (type(v) == 'number') then
1572 return my_class(self.val - v)
1575 -- assume both operands are instances of my_class
1576 return my_class(self.val - v.val)
1581 The reason why ``__sub`` is used as an example is because subtraction is not
1582 commutative (the order of the operands matters). That's why luabind cannot
1583 change order of the operands to make the self reference always refer to the
1584 actual class instance.
1586 If you have two different Lua classes with an overloaded operator, the operator
1587 of the right hand side type will be called. If the other operand is a C++ class
1588 with the same operator overloaded, it will be prioritized over the Lua class'
1589 operator. If none of the C++ overloads matches, the Lua class operator will be
1596 If an object needs to perform actions when it's collected we provide a
1597 ``__finalize`` function that can be overridden in lua-classes. The
1598 ``__finalize`` functions will be called on all classes in the inheritance
1599 chain, starting with the most derived type. ::
1603 function lua_testclass:__finalize()
1604 -- called when the an object is collected
1611 If your lua C++ classes don't have wrappers (see `Deriving in lua`_) and
1612 you derive from them in lua, they may be sliced. Meaning, if an object
1613 is passed into C++ as a pointer to its base class, the lua part will be
1614 separated from the C++ base part. This means that if you call virtual
1615 functions on that C++ object, they will not be dispatched to the lua
1616 class. It also means that if you adopt the object, the lua part will be
1621 +--------------------+
1622 | C++ object | <- ownership of this part is transferred
1623 | | to c++ when adopted
1624 +--------------------+
1625 | lua class instance | <- this part is garbage collected when
1626 | and lua members | instance is adopted, since it cannot
1627 +--------------------+ be held by c++.
1630 The problem can be illustrated by this example::
1634 A* filter_a(A* a) { return a; }
1635 void adopt_a(A* a) { delete a; }
1640 using namespace luabind;
1645 def("filter_a", &filter_a),
1646 def("adopt_a", &adopt_a, adopt(_1))
1656 In this example, lua cannot know that ``b`` actually is the same object as
1657 ``a``, and it will therefore consider the object to be owned by the C++ side.
1658 When the ``b`` pointer then is adopted, a runtime error will be raised because
1659 an object not owned by lua is being adopted to C++.
1661 If you have a wrapper for your class, none of this will happen, see
1668 If any of the functions you register throws an exception when called, that
1669 exception will be caught by luabind and converted to an error string and
1670 ``lua_error()`` will be invoked. If the exception is a ``std::exception`` or a
1671 ``const char*`` the string that is pushed on the Lua stack, as error message,
1672 will be the string returned by ``std::exception::what()`` or the string itself
1673 respectively. If the exception is unknown, a generic string saying that the
1674 function threw an exception will be pushed.
1676 If you have an exception type that isn't derived from
1677 ``std::exception``, or you wish to change the error message from the
1678 default result of ``what()``, it is possible to register custom
1679 exception handlers::
1684 void translate_my_exception(lua_State* L, my_exception const&)
1686 lua_pushstring(L, "my_exception");
1691 luabind::register_exception_handler<my_exception>(&translate_my_exception);
1693 ``translate_my_exception()`` will be called by luabind whenever a
1694 ``my_exception`` is caught. ``lua_error()`` will be called after the
1695 handler function returns, so it is expected that the function will push
1696 an error string on the stack.
1698 Any function that invokes Lua code may throw ``luabind::error``. This exception
1699 means that a Lua run-time error occurred. The error message is found on top of
1700 the Lua stack. The reason why the exception doesn't contain the error string
1701 itself is because it would then require heap allocation which may fail. If an
1702 exception class throws an exception while it is being thrown itself, the
1703 application will be terminated.
1705 Error's synopsis is::
1707 class error : public std::exception
1711 lua_State* state() const throw();
1712 virtual const char* what() const throw();
1715 The state function returns a pointer to the Lua state in which the error was
1716 thrown. This pointer may be invalid if you catch this exception after the lua
1717 state is destructed. If the Lua state is valid you can use it to retrieve the
1718 error message from the top of the Lua stack.
1720 An example of where the Lua state pointer may point to an invalid state
1725 lua_state(lua_State* L): m_L(L) {}
1726 ~lua_state() { lua_close(m_L); }
1727 operator lua_State*() { return m_L; }
1735 lua_state L = lua_open();
1738 catch(luabind::error& e)
1740 lua_State* L = e.state();
1741 // L will now point to the destructed
1742 // Lua state and be invalid
1747 There's another exception that luabind may throw: ``luabind::cast_failed``,
1748 this exception is thrown from ``call_function<>`` or ``call_member<>``. It
1749 means that the return value from the Lua function couldn't be converted to
1750 a C++ value. It is also thrown from ``object_cast<>`` if the cast cannot
1753 The synopsis for ``luabind::cast_failed`` is::
1755 class cast_failed : public std::exception
1758 cast_failed(lua_State*);
1759 lua_State* state() const throw();
1760 LUABIND_TYPE_INFO info() const throw();
1761 virtual const char* what() const throw();
1764 Again, the state member function returns a pointer to the Lua state where the
1765 error occurred. See the example above to see where this pointer may be invalid.
1767 The info member function returns the user defined ``LUABIND_TYPE_INFO``, which
1768 defaults to a ``const std::type_info*``. This type info describes the type that
1769 we tried to cast a Lua value to.
1771 If you have defined ``LUABIND_NO_EXCEPTIONS`` none of these exceptions will be
1772 thrown, instead you can set two callback functions that are called instead.
1773 These two functions are only defined if ``LUABIND_NO_EXCEPTIONS`` are defined.
1777 luabind::set_error_callback(void(*)(lua_State*))
1779 The function you set will be called when a runtime-error occur in Lua code. You
1780 can find an error message on top of the Lua stack. This function is not
1781 expected to return, if it does luabind will call ``std::terminate()``.
1785 luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
1787 The function you set is called instead of throwing ``cast_failed``. This function
1788 is not expected to return, if it does luabind will call ``std::terminate()``.
1794 Sometimes it is necessary to control how luabind passes arguments and return
1795 value, to do this we have policies. All policies use an index to associate
1796 them with an argument in the function signature. These indices are ``result``
1797 and ``_N`` (where ``N >= 1``). When dealing with member functions ``_1`` refers
1798 to the ``this`` pointer.
1800 .. contents:: Policies currently implemented
1804 .. include:: adopt.rst
1805 .. include:: dependency.rst
1806 .. include:: out_value.rst
1807 .. include:: pure_out_value.rst
1808 .. include:: return_reference_to.rst
1809 .. include:: copy.rst
1810 .. include:: discard_result.rst
1811 .. include:: return_stl_iterator.rst
1812 .. include:: raw.rst
1813 .. include:: yield.rst
1815 .. old policies section
1816 ===================================================
1821 This will make a copy of the parameter. This is the default behavior when
1822 passing parameters by-value. Note that this can only be used when passing from
1823 C++ to Lua. This policy requires that the parameter type has a copy
1826 To use this policy you need to include ``luabind/copy_policy.hpp``.
1832 This will transfer ownership of the parameter.
1834 Consider making a factory function in C++ and exposing it to lua::
1845 def("create_base", create_base)
1848 Here we need to make sure Lua understands that it should adopt the pointer
1849 returned by the factory-function. This can be done using the adopt-policy.
1855 def(L, "create_base", adopt(return_value))
1858 To specify multiple policies we just separate them with '+'.
1862 base* set_and_get_new(base* ptr)
1864 base_ptrs.push_back(ptr);
1870 def("set_and_get_new", &set_and_get_new,
1871 adopt(return_value) + adopt(_1))
1874 When Lua adopts a pointer, it will call delete on it. This means that it cannot
1875 adopt pointers allocated with another allocator than new (no malloc for
1878 To use this policy you need to include ``luabind/adopt_policy.hpp``.
1884 The dependency policy is used to create life-time dependencies between values.
1885 Consider the following example::
1891 const B& get_member()
1897 When wrapping this class, we would do something like::
1902 .def(constructor<>())
1903 .def("get_member", &A::get_member)
1907 However, since the return value of get_member is a reference to a member of A,
1908 this will create some life-time issues. For example::
1910 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1912 b = a:get_member() -- b points to a member of a
1914 collectgarbage(0) -- since there are no references left to a, it is
1916 -- at this point, b is pointing into a removed object
1918 When using the dependency-policy, it is possible to tell luabind to tie the
1919 lifetime of one object to another, like this::
1924 .def(constructor<>())
1925 .def("get_member", &A::get_member, dependency(result, _1))
1928 This will create a dependency between the return-value of the function, and the
1929 self-object. This means that the self-object will be kept alive as long as the
1930 result is still alive. ::
1932 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
1934 b = a:get_member() -- b points to a member of a
1936 collectgarbage(0) -- a is dependent on b, so it isn't removed
1938 collectgarbage(0) -- all dependencies to a gone, a is removed
1940 To use this policy you need to include ``luabind/dependency_policy.hpp``.
1946 It is very common to return references to arguments or the this-pointer to
1947 allow for chaining in C++.
1962 When luabind generates code for this, it will create a new object for the
1963 return-value, pointing to the self-object. This isn't a problem, but could be a
1964 bit inefficient. When using the return_reference_to-policy we have the ability
1965 to tell luabind that the return-value is already on the Lua stack.
1972 .def(constructor<>())
1973 .def("set", &A::set, return_reference_to(_1))
1976 Instead of creating a new object, luabind will just copy the object that is
1977 already on the stack.
1980 This policy ignores all type information and should be used only it
1981 situations where the parameter type is a perfect match to the
1982 return-type (such as in the example).
1984 To use this policy you need to include ``luabind/return_reference_to_policy.hpp``.
1990 This policy makes it possible to wrap functions that take non const references
1991 as its parameters with the intention to write return values to them.
1995 void f(float& val) { val = val + 10.f; }
2001 void f(float* val) { *val = *val + 10.f; }
2003 Can be wrapped by doing::
2007 def("f", &f, out_value(_1))
2010 When invoking this function from Lua it will return the value assigned to its
2015 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
2020 When this policy is used in conjunction with user define types we often need
2021 to do ownership transfers.
2027 void f1(A*& obj) { obj = new A(); }
2028 void f2(A** obj) { *obj = new A(); }
2030 Here we need to make sure luabind takes control over object returned, for
2031 this we use the adopt policy::
2036 def("f1", &f1, out_value(_1, adopt(_2)))
2037 def("f2", &f2, out_value(_1, adopt(_2)))
2040 Here we are using adopt as an internal policy to out_value. The index
2041 specified, _2, means adopt will be used to convert the value back to Lua.
2042 Using _1 means the policy will be used when converting from Lua to C++.
2044 To use this policy you need to include ``luabind/out_value_policy.hpp``.
2049 This policy works in exactly the same way as out_value, except that it
2050 replaces the parameters with default-constructed objects.
2054 void get(float& x, float& y)
2065 pure_out_value(_1) + pure_out_value(_2))
2070 Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
2075 Like out_value, it is possible to specify an internal policy used then
2076 converting the values back to Lua.
2080 void get(test_class*& obj)
2082 obj = new test_class();
2089 def("get", &get, pure_out_value(_1, adopt(_1)))
2096 This is a very simple policy which makes it possible to throw away
2097 the value returned by a C++ function, instead of converting it to
2098 Lua. This example makes sure the this reference never gets converted
2105 simple& set_name(const std::string& n)
2118 class_<simple>("simple")
2119 .def("set_name", &simple::set_name, discard_result)
2122 To use this policy you need to include ``luabind/discard_result_policy.hpp``.
2128 This policy converts an STL container to a generator function that can be used
2129 in Lua to iterate over the container. It works on any container that defines
2130 ``begin()`` and ``end()`` member functions (they have to return iterators). It
2131 can be used like this::
2135 std::vector<std::string> names;
2142 .def_readwrite("names", &A::names, return_stl_iterator)
2145 The Lua code to iterate over the container::
2149 for name in a.names do
2154 To use this policy you need to include ``luabind/iterator_policy.hpp``.
2160 This policy will cause the function to always yield the current thread when
2161 returning. See the Lua manual for restrictions on yield.
2164 Splitting up the registration
2165 =============================
2167 It is possible to split up a module registration into several
2168 translation units without making each registration dependent
2169 on the module it's being registered in.
2173 luabind::scope register_a()
2183 luabind::scope register_b()
2193 luabind::scope register_a();
2194 luabind::scope register_b();
2196 void register_module(lua_State* L)
2212 As mentioned in the `Lua documentation`_, it is possible to pass an
2213 error handler function to ``lua_pcall()``. Luabind makes use of
2214 ``lua_pcall()`` internally when calling member functions and free functions.
2215 It is possible to set the error handler function that Luabind will use
2218 typedef int(*pcall_callback_fun)(lua_State*);
2219 void set_pcall_callback(pcall_callback_fun fn);
2221 This is primarily useful for adding more information to the error message
2222 returned by a failed protected call. For more information on how to use the
2223 pcall_callback function, see ``errfunc`` under the
2224 `pcall section of the lua manual`_.
2226 For more information on how to retrieve debugging information from lua, see
2227 `the debug section of the lua manual`_.
2229 The message returned by the ``pcall_callback`` is accessable as the top lua
2230 value on the stack. For example, if you would like to access it as a luabind
2231 object, you could do like this::
2235 object error_msg(from_stack(e.state(), -1));
2236 std::cout << error_msg << std::endl;
2239 .. _Lua documentation: http://www.lua.org/manual/5.0/manual.html
2240 .. _`pcall section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#3.15
2241 .. _`the debug section of the lua manual`: http://www.lua.org/manual/5.0/manual.html#4
2243 file and line numbers
2244 ---------------------
2246 If you want to add file name and line number to the error messages generated
2247 by luabind you can define your own `pcall errorfunc`_. You may want to modify
2248 this callback to better suit your needs, but the basic functionality could be
2249 implemented like this::
2251 int add_file_and_line(lua_State* L)
2254 lua_getstack(L, 1, &d);
2255 lua_getinfo(L, "Sln", &d);
2256 std::string err = lua_tostring(L, -1);
2258 std::stringstream msg;
2259 msg << d.short_src << ":" << d.currentline;
2263 msg << "(" << d.namewhat << " " << d.name << ")";
2266 lua_pushstring(L, msg.str().c_str());
2270 For more information about what kind of information you can add to the error
2271 message, see `the debug section of the lua manual`_.
2273 Note that the callback set by ``set_pcall_callback()`` will only be used when
2274 luabind executes lua code. Anytime when you call ``lua_pcall`` yourself, you
2275 have to supply your function if you want error messages translated.
2280 When lua encounters a fatal error caused by a bug from the C/C++ side, it will
2281 call its internal panic function. This can happen, for example, when you call
2282 ``lua_gettable`` on a value that isn't a table. If you do the same thing from
2283 within lua, it will of course just fail with an error message.
2285 The default panic function will ``exit()`` the application. If you want to
2286 handle this case without terminating your application, you can define your own
2287 panic function using ``lua_atpanic``. The best way to continue from the panic
2288 function is to make sure lua is compiled as C++ and throw an exception from
2289 the panic function. Throwing an exception instead of using ``setjmp`` and
2290 ``longjmp`` will make sure the stack is correctly unwound.
2292 When the panic function is called, the lua state is invalid, and the only
2293 allowed operation on it is to close it.
2295 For more information, see the `lua manual section 3.19`_.
2297 .. _`lua manual section 3.19`: http://www.lua.org/manual/5.0/manual.html#3.19
2299 structured exceptions (MSVC)
2300 ----------------------------
2302 Since lua is generally built as a C library, any callbacks called from lua
2303 cannot under any circumstance throw an exception. Because of that, luabind has
2304 to catch all exceptions and translate them into proper lua errors (by calling
2305 ``lua_error()``). This means we have a ``catch(...) {}`` in there.
2307 In Visual Studio, ``catch (...)`` will not only catch C++ exceptions, it will
2308 also catch structured exceptions, such as segmentation fault. This means that if
2309 your function, that gets called from luabind, makes an invalid memory
2310 adressing, you won't notice it. All that will happen is that lua will return
2311 an error message saying "unknown exception".
2313 To remedy this, you can create your own *exception translator*::
2315 void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
2319 ::_set_se_translator(straight_to_debugger);
2322 This will make structured exceptions, like segmentation fault, to actually get
2323 caught by the debugger.
2329 These are the error messages that can be generated by luabind, with a more
2330 in-depth explanation.
2332 - .. parsed-literal::
2334 the attribute '*class-name.attribute-name*' is read only
2336 There is no data member named *attribute-name* in the class *class-name*,
2337 or there's no setter-function registered on that property name. See the
2338 Properties_ section.
2340 - .. parsed-literal::
2342 the attribute '*class-name.attribute-name*' is of type: (*class-name*) and does not match (*class_name*)
2344 This error is generated if you try to assign an attribute with a value
2345 of a type that cannot be converted to the attribute's type.
2348 - .. parsed-literal::
2350 *class-name()* threw an exception, *class-name:function-name()* threw an exception
2352 The class' constructor or member function threw an unknown exception.
2353 Known exceptions are const char*, std::exception. See the
2354 `exceptions`_ section.
2356 - .. parsed-literal::
2358 no overload of '*class-name:function-name*' matched the arguments (*parameter-types*)
2359 no match for function call '*function-name*' with the parameters (*parameter-types*)
2360 no constructor of *class-name* matched the arguments (*parameter-types*)
2361 no operator *operator-name* matched the arguments (*parameter-types*)
2363 No function/operator with the given name takes the parameters you gave
2364 it. You have either misspelled the function name, or given it incorrect
2365 parameters. This error is followed by a list of possible candidate
2366 functions to help you figure out what parameter has the wrong type. If
2367 the candidate list is empty there's no function at all with that name.
2368 See the signature matching section.
2370 - .. parsed-literal::
2372 call of overloaded '*class-name:function-name*(*parameter-types*)' is ambiguous
2373 ambiguous match for function call '*function-name*' with the parameters (*parameter-types*)
2374 call of overloaded constructor '*class-name*(*parameter-types*)' is ambiguous
2375 call of overloaded operator *operator-name* (*parameter-types*) is ambiguous
2377 This means that the function/operator you are trying to call has at least
2378 one other overload that matches the arguments just as good as the first
2381 - .. parsed-literal::
2383 cannot derive from C++ class '*class-name*'. It does not have a wrapped type.
2390 There are a number of configuration options available when building luabind.
2391 It is very important that your project has the exact same configuration
2392 options as the ones given when the library was build! The exceptions are the
2393 ``LUABIND_MAX_ARITY`` and ``LUABIND_MAX_BASES`` which are template-based
2394 options and only matters when you use the library (which means they can
2395 differ from the settings of the library).
2397 The default settings which will be used if no other settings are given
2398 can be found in ``luabind/config.hpp``.
2400 If you want to change the settings of the library, you can modify the
2401 config file. It is included and used by all makefiles. You can change paths
2402 to Lua and boost in there as well.
2405 Controls the maximum arity of functions that are registered with luabind.
2406 You can't register functions that takes more parameters than the number
2407 this macro is set to. It defaults to 5, so, if your functions have greater
2408 arity you have to redefine it. A high limit will increase compilation time.
2411 Controls the maximum number of classes one class can derive from in
2412 luabind (the number of classes specified within ``bases<>``).
2413 ``LUABIND_MAX_BASES`` defaults to 4. A high limit will increase
2416 LUABIND_NO_ERROR_CHECKING
2417 If this macro is defined, all the Lua code is expected only to make legal
2418 calls. If illegal function calls are made (e.g. giving parameters that
2419 doesn't match the function signature) they will not be detected by luabind
2420 and the application will probably crash. Error checking could be disabled
2421 when shipping a release build (given that no end-user has access to write
2422 custom Lua code). Note that function parameter matching will be done if a
2423 function is overloaded, since otherwise it's impossible to know which one
2424 was called. Functions will still be able to throw exceptions when error
2425 checking is disabled.
2427 If a function throws an exception it will be caught by luabind and
2428 propagated with ``lua_error()``.
2430 LUABIND_NO_EXCEPTIONS
2431 This define will disable all usage of try, catch and throw in luabind.
2432 This will in many cases disable run-time errors, when performing invalid
2433 casts or calling Lua functions that fails or returns values that cannot
2434 be converted by the given policy. luabind requires that no function called
2435 directly or indirectly by luabind throws an exception (throwing exceptions
2436 through Lua has undefined behavior).
2438 Where exceptions are the only way to get an error report from luabind,
2439 they will be replaced with calls to the callback functions set with
2440 ``set_error_callback()`` and ``set_cast_failed_callback()``.
2443 If you want to link dynamically against Lua, you can set this define to
2444 the import-keyword on your compiler and platform. On Windows in Visual Studio
2445 this should be ``__declspec(dllimport)`` if you want to link against Lua
2448 LUABIND_EXPORT, LUABIND_IMPORT
2449 If you want to link against luabind as a dll (in Visual Studio), you can
2450 define ``LUABIND_EXPORT`` to ``__declspec(dllexport)`` and
2451 ``LUABIND_IMPORT`` to ``__declspec(dllimport)`` or
2452 ``__attribute__ ((visibility("default")))`` on GCC 4.
2453 Note that you have to link against Lua as a dll aswell, to make it work.
2456 You can define this if you don't want luabind to use ``dynamic_cast<>``.
2457 It will disable `Object identity`_.
2459 LUABIND_TYPE_INFO, LUABIND_TYPE_INFO_EQUAL(i1,i2), LUABIND_TYPEID(t), LUABIND_INVALID_TYPE_INFO
2460 If you don't want to use the RTTI supplied by C++ you can supply your own
2461 type-info structure with the ``LUABIND_TYPE_INFO`` define. Your type-info
2462 structure must be copyable and must be able to compare itself against
2463 other type-info structures. You supply the compare function through the
2464 ``LUABIND_TYPE_INFO_EQUAL()`` define. It should compare the two type-info
2465 structures it is given and return true if they represent the same type and
2466 false otherwise. You also have to supply a function to generate your
2467 type-info structure. You do this through the ``LUABIND_TYPEID()`` define.
2468 It should return your type-info structure and it takes a type as its
2469 parameter. That is, a compile time parameter.
2470 ``LUABIND_INVALID_TYPE_INFO`` macro should be defined to an invalid type.
2471 No other type should be able to produce this type info. To use it you
2472 probably have to make a traits class with specializations for all classes
2473 that you have type-info for. Like this::
2479 template<class T> struct typeinfo_trait;
2481 template<> struct typeinfo_trait<A> { enum { type_id = 0 }; };
2482 template<> struct typeinfo_trait<B> { enum { type_id = 1 }; };
2483 template<> struct typeinfo_trait<C> { enum { type_id = 2 }; };
2485 If you have set up your own RTTI system like this (by using integers to
2486 identify types) you can have luabind use it with the following defines::
2488 #define LUABIND_TYPE_INFO const std::type_info*
2489 #define LUABIND_TYPEID(t) &typeid(t)
2490 #define LUABIND_TYPE_INFO_EQUAL(i1, i2) *i1 == *i2
2491 #define LUABIND_INVALID_TYPE_INFO &typeid(detail::null_type)
2493 Currently the type given through ``LUABIND_TYPE_INFO`` must be less-than
2497 This define will disable all asserts and should be defined in a release
2501 Implementation notes
2502 ====================
2504 The classes and objects are implemented as user data in Lua. To make sure that
2505 the user data really is the internal structure it is supposed to be, we tag
2506 their metatables. A user data who's metatable contains a boolean member named
2507 ``__luabind_classrep`` is expected to be a class exported by luabind. A user
2508 data who's metatable contains a boolean member named ``__luabind_class`` is
2509 expected to be an instantiation of a luabind class.
2511 This means that if you make your own user data and tags its metatable with the
2512 exact same names, you can very easily fool luabind and crash the application.
2514 In the Lua registry, luabind keeps an entry called ``__luabind_classes``. It
2515 should not be removed or overwritten.
2517 In the global table, a variable called ``super`` is used every time a
2518 constructor in a lua-class is called. This is to make it easy for that
2519 constructor to call its base class' constructor. So, if you have a global
2520 variable named super it may be overwritten. This is probably not the best
2521 solution, and this restriction may be removed in the future.
2523 .. note:: Deprecated
2525 ``super()`` has been deprecated since version 0.8 in favor of directly
2526 invoking the base class' ``__init()`` function::
2528 function Derived:__init()
2532 Luabind uses two upvalues for functions that it registers. The first is a
2533 userdata containing a list of overloads for the function, the other is a light
2534 userdata with the value 0x1337, this last value is used to identify functions
2535 registered by luabind. It should be virtually impossible to have such a pointer
2536 as secondary upvalue by pure chance. This means, if you are trying to replace
2537 an existing function with a luabind function, luabind will see that the
2538 secondary upvalue isn't the magic id number and replace it. If it can identify
2539 the function to be a luabind function, it won't replace it, but rather add
2540 another overload to it.
2542 Inside the luabind namespace, there's another namespace called detail. This
2543 namespace contains non-public classes and are not supposed to be used directly.
2549 What's up with __cdecl and __stdcall?
2550 If you're having problem with functions
2551 that cannot be converted from ``void (__stdcall *)(int,int)`` to
2552 ``void (__cdecl*)(int,int)``. You can change the project settings to make the
2553 compiler generate functions with __cdecl calling conventions. This is
2554 a problem in developer studio.
2556 What's wrong with functions taking variable number of arguments?
2557 You cannot register a function with ellipses in its signature. Since
2558 ellipses don't preserve type safety, those should be avoided anyway.
2560 Internal structure overflow in VC
2561 If you, in visual studio, get fatal error C1204: compiler limit :
2562 internal structure overflow. You should try to split that compilation
2563 unit up in smaller ones. See `Splitting up the registration`_ and
2564 `Splitting class registrations`_.
2566 What's wrong with precompiled headers in VC?
2567 Visual Studio doesn't like anonymous namespace's in its precompiled
2568 headers. If you encounter this problem you can disable precompiled
2569 headers for the compilation unit (cpp-file) that uses luabind.
2571 error C1076: compiler limit - internal heap limit reached in VC
2572 In visual studio you will probably hit this error. To fix it you have to
2573 increase the internal heap with a command-line option. We managed to
2574 compile the test suit with /Zm300, but you may need a larger heap then
2577 error C1055: compiler limit \: out of keys in VC
2578 It seems that this error occurs when too many assert() are used in a
2579 program, or more specifically, the __LINE__ macro. It seems to be fixed by
2580 changing /ZI (Program database for edit and continue) to /Zi
2583 How come my executable is huge?
2584 If you're compiling in debug mode, you will probably have a lot of
2585 debug-info and symbols (luabind consists of a lot of functions). Also,
2586 if built in debug mode, no optimizations were applied, luabind relies on
2587 that the compiler is able to inline functions. If you built in release
2588 mode, try running strip on your executable to remove export-symbols,
2589 this will trim down the size.
2591 Our tests suggests that cygwin's gcc produces much bigger executables
2592 compared to gcc on other platforms and other compilers.
2594 .. HUH?! // check the magic number that identifies luabind's functions
2596 Can I register class templates with luabind?
2597 Yes you can, but you can only register explicit instantiations of the
2598 class. Because there's no Lua counterpart to C++ templates. For example,
2599 you can register an explicit instantiation of std::vector<> like this::
2603 class_<std::vector<int> >("vector")
2604 .def(constructor<int>)
2605 .def("push_back", &std::vector<int>::push_back)
2608 .. Again, irrelevant to docs: Note that the space between the two > is required by C++.
2610 Do I have to register destructors for my classes?
2611 No, the destructor of a class is always called by luabind when an
2612 object is collected. Note that Lua has to own the object to collect it.
2613 If you pass it to C++ and gives up ownership (with adopt policy) it will
2614 no longer be owned by Lua, and not collected.
2616 If you have a class hierarchy, you should make the destructor virtual if
2617 you want to be sure that the correct destructor is called (this apply to C++
2620 .. And again, the above is irrelevant to docs. This isn't a general C++ FAQ. But it saves us support questions.
2622 Fatal Error C1063 compiler limit \: compiler stack overflow in VC
2623 VC6.5 chokes on warnings, if you are getting alot of warnings from your
2624 code try suppressing them with a pragma directive, this should solve the
2627 Crashes when linking against luabind as a dll in Windows
2628 When you build luabind, Lua and you project, make sure you link against
2629 the runtime dynamically (as a dll).
2631 I cannot register a function with a non-const parameter
2632 This is because there is no way to get a reference to a Lua value. Have
2633 a look at out_value_ and pure_out_value_ policies.
2639 - You cannot use strings with extra nulls in them as member names that refers
2642 - If one class registers two functions with the same name and the same
2643 signature, there's currently no error. The last registered function will
2644 be the one that's used.
2646 - In VC7, classes can not be called test.
2648 - If you register a function and later rename it, error messages will use the
2649 original function name.
2651 - luabind does not support class hierarchies with virtual inheritance. Casts are
2652 done with static pointer offsets.
2658 Written by Daniel Wallin and Arvid Norberg. © Copyright 2003.
2659 All rights reserved.
2661 Evan Wies has contributed with thorough testing, countless bug reports
2664 This library was highly inspired by Dave Abrahams' Boost.Python_ library.
2666 .. _Boost.Python: http://www.boost.org/libraries/python