Provided by: libluabind-dev_0.9.1+git20150823+dfsg-2build1_amd64 bug


       luabind - Luabind Documentation

       This is the documentation for Luabind 0.9.1d1 .

       Luabind  is  a  library  that  helps  you  create bindings between C++ and Lua. It has the
       ability to expose functions and classes, written in C++, to Lua.  It will also supply  the
       functionality  to  define classes in Lua and let them derive from other Lua classes or C++
       classes. Lua classes can override virtual functions from their C++  base  classes.  It  is
       written towards Lua 5.2 but should also work with 5.1.

       The old official homepage can be found at



       Luabind  is  a  library  that  helps  you  create bindings between C++ and Lua. It has the
       ability to expose functions and classes, written in C++, to Lua. It will also  supply  the
       functionality  to  define classes in Lua and let them derive from other Lua classes or C++
       classes. Lua classes can override virtual functions from their C++  base  classes.  It  is
       written towards Lua 5.2 but should also work with 5.1.

       It  is  implemented utilizing template meta programming. That means that you don't need an
       extra preprocess pass to compile your project (it is done by the compiler). It also  means
       you  don't (usually) have to know the exact signature of each function you register, since
       the library will generate code depending on the compile-time type of the  function  (which
       includes  the  signature). The main drawback of this approach is that the compilation time
       will increase for the file that does the registration, it is  therefore  recommended  that
       you register everything in the same cpp-file.

       Luabind is released under the terms of the MIT license.

       We  are  very  interested  in  hearing about projects that use luabind, please let us know
       about your project.

       The main channel for help and feedback is the luabind mailing list.  There's also  an  IRC
       channel #luabind on

       Additionally,  this  fork’s github issue tracker can also be used for bug reports, feature
       requests and questions.


       Luabind supports:

          · Overloaded free functions

          · C++ classes in Lua

          · Overloaded member functions

          · Operators

          · Properties

          · Enums (also C++11 enum class if available)

          · Lua functions in C++

          · Lua classes in C++

          · Lua classes (single inheritance)

          · Derives from Lua or C++ classes

          · Override virtual functions from C++ classes

          · Implicit casts between registered types

          · Best match signature matching

          · Return value policies and parameter policies


       Luabind is currently tested regularly with

          · Microsoft Visual C++ 11 (2012) x32 and x64

          · gcc 4.8 x64 (with and without -std=c++11)

          · Clang 3.2 x64 (with and without -std=c++11)

       It should work with any compiler conformant with C++03. However, probably only versions of
       the  above  threecompilers  will  work out of the box with the provided CMake build files.
       Please report any issues you have to the github issue tracker.


       Apart from Lua 5.1 or (recommended) 5.2, Luabind depends on a number of  Boost  libraries.
       It also depends on CMake to build the library and run the tests.

       If  CMake  has  problems  finding  Lua,  LUA_DIR  needs  to be set to point to a directory
       containing the Lua include directory and built libraries.

       The same applies to Boost and the BOOST_ROOT environment variable.

   Linux and other *nix flavors
       If your system already has Lua installed, it is very likely that  the  build  system  will
       automatically find it and just work. If you have Lua installed in a non-standard location,
       you may need to set LUA_DIR to point to the installation prefix.

       BOOST_ROOT can be set to a Boost installation directory. If left unset, the  build  system
       will try to use boost headers from the standard include path.

   Building and testing
       Building  the default variant of the library, which is a static release library, is simply
       done by invoking cmake in the luabind root directory and then running  your  native  build
       tools  on  the  generated  files (e.g. make on Unix or nmake/msbuild ALL_BUILD.vcxproj for

          To build your application against  the  shared  library  variant,  LUABIND_DYNAMIC_LINK
          needs to be defined to properly import symbols.

       To  run  the  unit  tests, invoke your build tool with the test target, e.g.  make test on
       Unix or nmake test/msbuild RUN_TESTS.vcxproj for MSVC.  This run  the  (previously  built)
       unit tests in the current variant. A clean test run output should end with something like:

          100% tests passed, 0 tests failed out of 51
          Total Test time (real) =   1.23 sec

       A failed run would end with something like:

          98% tests passed, 1 tests failed out of 51

          Total Test time (real) =   1.23 sec

          The following tests FAILED:
              1 - abstract_base (Failed)


       To use luabind, you must include lua.h and luabind's main header file:

          extern "C"
              #include "lua.h"

          #include <luabind/luabind.hpp>

       This includes support for both registering classes and functions. If you just want to have
       support  for   functions   or   classes   you   can   include   luabind/function.hpp   and
       luabind/class.hpp separately:

          #include <luabind/function.hpp>
          #include <luabind/class.hpp>

       The  first  thing  you need to do is to call luabind::open(lua_State*) which will register
       the functions to create classes from Lua, and initialize some state-global structures used
       by  luabind.  If  you  don't call this function you will hit asserts later in the library.
       There is no corresponding close function because once a class has been registered in  Lua,
       there  really  isn't  any good way to remove it. Partly because any remaining instances of
       that class relies on the class being there. Everything will be cleaned up when  the  state
       is closed though.

       Luabind's     headers     will    never    include    lua.h    directly,    but    through
       <luabind/lua_include.hpp>. If you for some reason need to include another Lua header,  you
       can modify this file.

   Hello world
          #include <iostream>
          #include <luabind/luabind.hpp>

          void greet()
              std::cout << "hello world!\n";

          extern "C" int init(lua_State* L)
              using namespace luabind;


                  def("greet", &greet)

              return 0;

          Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
          > loadlib('hello_world.dll', 'init')()
          > greet()
          Hello world!


       Everything  that gets registered in Lua is registered in a given Lua table, in a namespace
       (Lua table at given name), or in the global scope (called module).  All registrations must
       be  surrounded  by its scope. To define a module, the luabind::module class is used. It is
       used like this:

              // declarations

       This will register all declared functions or classes in the global namespace in Lua.

       You can also register into a custom Lua table wrapped in a part-object:

          object mod = newtable(L);
          module(L, mod)
              // declarations

       You can then directly use all object manipulation functions on mod.

       If you just want to have a namespace for your module (like the standard libraries) you can
       give a name to the constructor, like this:

          module(L, "my_library")
              // declarations

       Here all declarations will be put in the my_library table.

       If you want nested namespace's you can use the luabind::namespace_ class. It works exactly
       as luabind::module except that it doesn't  take  a  lua_State*  in  it's  constructor.  An
       example of its usage could look like this:

          module(L, "my_library")
              // declarations

                  // library-private declarations

       As you might have figured out, the following declarations are equivalent:

                  // declarations


          module(L, "my_library")
              // declarations

       Each declaration must be separated by a comma, like this:

              def("f", &f),
              def("g", &g),
                  .def(constructor<int, int>),
              def("h", &h)

       More about the actual declarations in the part-functions and part-classes sections.


       To  bind  functions  to  Lua  you  use  the  function luabind::def(). It has the following

          template<class F, class policies>
          void def(const char* name, F f, const Policies&);

       · name is the name the function will have within Lua.

       · F is the function pointer you want to register.

       · The Policies parameter is used to describe how parameters and return values are  treated
         by  the  function,  this  is  an  optional  parameter. More on this in the part-policies

       An example usage could be if you want to register the function float std::sin(float):

              def("sin", &std::sin)

   Overloaded functions
       If you have more than one function with the same name, and want to register them  in  Lua,
       you  have  to  explicitly  give  the signature. This is to let C++ know which function you
       refer to. For example, if you have two functions, int f(const char*) and void f(int).

              def("f", (int(*)(const char*)) &f),
              def("f", (void(*)(int)) &f)

   Signature matching
       luabind will generate code that checks the Lua stack to see if the values there can  match
       your functions' signatures. It will handle implicit typecasts between derived classes, and
       it will prefer matches with the least number of implicit casts. In a function call, if the
       function  is  overloaded and there's no overload that match the parameters better than the
       other, you have an ambiguity. This will spawn a run-time error, stating that the  function
       call  is ambiguous. A simple example of this is to register one function that takes an int
       and one that takes a float. Since Lua doesn't distinguish  between  floats  and  integers,
       both will always match.

       Since  all overloads are tested, it will always find the best match (not the first match).
       This also means that it can handle situations where the only difference in  the  signature
       is that one member function is const and the other isn't.

   Ownership transfer
       To  correctly  handle  ownership  transfer,  create_a()  would  need an adopt return value
       policy. More on this in the part-policies section.

       For example, if the following function and class is registered:

          struct A
              void f();
              void f() const;

          const A* create_a();

          struct B: A {};
          struct C: B {};

          void g(A*);
          void g(B*);

       And the following Lua code is executed:

          a1 = create_a()
          a1:f() -- the const version is called

          a2 = A()
          a2:f() -- the non-const version is called

          a = A()
          b = B()
          c = C()

          g(a) -- calls g(A*)
          g(b) -- calls g(B*)
          g(c) -- calls g(B*)

   Calling Lua functions
       To call a Lua function, you can either use call_function() or an object.

          template<class Ret>
          Ret call_function(lua_State* L, const char* name, ...)
          template<class Ret>
          Ret call_function(object const& obj, ...)

       There are two overloads of the call_function function, one that calls a function given its
       name,  and  one  that  takes  an object that should be a Lua value that can be called as a

       The overload that takes a name can only call global Lua functions. The ...   represents  a
       variable  number  of  parameters that are sent to the Lua function. This function call may
       throw luabind::error if the function call fails.

       The return value isn't actually Ret (the template parameter), but a proxy object that will
       do  the function call. This enables you to give policies to the call. You do this with the
       operator[]. You give the policies within the brackets, like this:

          int ret = call_function<int>(
            , "a_lua_function"
            , new complex_class()
          )[ adopt(_1) ];

       If you want to pass a parameter as a reference, you have to wrap it with the Boost.Ref.

       Like this:

          int ret = call_function(L, "fun", boost::ref(val));

       If you want to use a custom error handler for the function  call,  see  set_pcall_callback
       under sec-pcall-errorfunc.

   Using Lua threads
       To  start  a Lua thread, you have to call lua_resume(), this means that you cannot use the
       previous function call_function() to start a thread. You have to use

          template<class Ret>
          Ret resume_function(lua_State* L, const char* name, ...)
          template<class Ret>
          Ret resume_function(object const& obj, ...)


          template<class Ret>
          Ret resume(lua_State* L, ...)

       The first time you start the thread, you have to give it a function to execute.  i.e.  you
       have  to use resume_function, when the Lua function yields, it will return the first value
       passed in to lua_yield(). When you want to continue the execution, you just call  resume()
       on  your  lua_State,  since  it's already executing a function, you don't pass it one. The
       parameters to resume() will be returned by yield() on the Lua side.

       For yielding C++-functions (without the support of passing data back and forth between the
       Lua side and the c++ side), you can use the policy-yield policy.

       With  the  overload of resume_function that takes an part-object, it is important that the
       object was constructed with the thread as its lua_State*. Like this:

          lua_State* thread = lua_newthread(L);
          object fun = get_global(thread)["my_thread_fun"];

   Binding function objects with explicit signatures
       Using luabind::tag_function<> it is possible to export function objects from which luabind
       can't  automatically  deduce a signature. This can be used to slightly alter the signature
       of a bound function, or even to bind stateful function objects.


          template <class Signature, class F>
          implementation-defined tag_function(F f);

       Where Signature is a function type describing the signature of F.  It  can  be  used  like

          int f(int x);

          // alter the signature so that the return value is ignored
          def("f", tag_function<void(int)>(f));

          struct plus
              plus(int x)
                : x(x)

              int operator()(int y) const
                  return x + y;

          // bind a stateful function object
          def("plus3", tag_function<int(int)>(plus(3)));


       To  register  classes  you use a class called class_. Its name is supposed to resemble the
       C++ keyword, to make it look more intuitive. It has an overloaded  member  function  def()
       that  is  used to register member functions, operators, constructors, enums and properties
       on the class. It will return its this-pointer, to let you register more members directly.

       Let's start with a simple example. Consider the following C++ class:

          class testclass
              testclass(const std::string& s): m_string(s) {}
              void print_string() { std::cout << m_string << "\n"; }

              std::string m_string;

       To register it with a Lua environment, write as follows (assuming you are using  namespace

                  .def(constructor<const std::string&>())
                  .def("print_string", &testclass::print_string)

       This  will  register the class with the name testclass and constructor that takes a string
       as argument and one member function with the name print_string.

          Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
          > a = testclass('a string')
          > a:print_string()
          a string

       It is also possible to register free functions as member functions. The requirement on the
       function  is  that  it takes a pointer, const pointer, reference or const reference to the
       class type as the first parameter. The rest of  the  parameters  are  the  ones  that  are
       visible  in  Lua, while the object pointer is given as the first parameter. If we have the
       following C++ code:

          struct A
              int a;

          int plus(A* o, int v) { return o->a + v; }

       You can register plus() as if it was a member function of A like this:

              .def("plus", &plus)

       plus() can now be called as a member function on A with one parameter, int.  If the object
       pointer parameter is const, the function will act as if it was a const member function (it
       can be called on const objects).

   Overloaded member functions
       When binding more than one overloads of a member function, or just binding one overload of
       an  overloaded  member  function, you have to disambiguate the member function pointer you
       pass to def. To do this, you can use an ordinary C-style cast, to cast  it  to  the  right
       overload. To do this, you have to know how to express member function types in C++, here's
       a short tutorial (for more info, refer to your favorite book on C++).

       The syntax for member function pointer follows:

          return-value (class-name::*)(arg1-type, arg2-type, ...)

       Here's an example illlustrating this:

          struct A
              void f(int);
              void f(int, int);

              .def("f", (void(A::*)(int))&A::f)

       This selects the first overload of the function f to bind.  The  second  overload  is  not

       To  register  a  global  data  member  with a class is easily done. Consider the following

          struct A
              int a;

       This class is registered like this:

                  .def_readwrite("a", &A::a)

       This gives read and write access to the member variable  A::a.  It  is  also  possible  to
       register attributes with read-only access:

                  .def_readonly("a", &A::a)

       When  binding  members  that  are a non-primitive type, the auto generated getter function
       will return a reference to it. This is to allow chained .-operators.   For  example,  when
       having a struct containing another struct. Like this:

          struct A { int m; };
          struct B { A a; };

       When binding B to lua, the following expression code should work:

          b = B()
          b.a.m = 1
          assert(b.a.m == 1)

       This  requires the first lookup (on a) to return a reference to A, and not a copy. In that
       case, luabind will automatically use the  dependency  policy  to  make  the  return  value
       dependent  on the object in which it is stored. So, if the returned reference lives longer
       than all references to the object (b in this case) it will keep the object alive, to avoid
       being a dangling pointer.

       You  can  also  register  getter and setter functions and make them look as if they were a
       public data member. Consider the following class:

          class A
              void set_a(int x) { a = x; }
              int get_a() const { return a; }

              int a;

       It can be registered as if it had a public data member a like this:

              .property("a", &A::get_a, &A::set_a)

       This way the get_a() and set_a() functions will be called instead of just writing  to  the
       data member. If you want to make it read only you can just omit the last parameter. Please
       note that the get function has to be const, otherwise it won't compile. This seems to be a
       common source of errors.

       If your class contains enumerated constants (enums), you can register them as well to make
       them available in Lua. Note that they will not be type safe, all  enums  are  integers  in
       Lua, and all functions that takes an enum, will accept any integer. You register them like

                      value("my_enum", 4),
                      value("my_2nd_enum", 7),
                      value("another_enum", 6)

       In Lua they are accessed like any data member, except that they are read-only and  reached
       on the class itself rather than on an instance of the class.

          Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
          > print(A.my_enum)
          > print(A.another_enum)

       To bind operators you have to include <luabind/operator.hpp>.

       The  mechanism  for registering operators on your class is pretty simple. You use a global
       name luabind::self to refer to the class itself and  then  you  just  write  the  operator
       expression inside the def() call. This class:

          struct vec
              vec operator+(int s);

       Is registered like this:

                  .def(self + int())

       This  will work regardless if your plus operator is defined inside your class or as a free

       If your operator is const (or, when defined as a free function, takes a const reference to
       the class itself) you have to use const_self instead of self. Like this:

                  .def(const_self + int())

       The operators supported are those available in Lua:

          +    -    *    /    ==    <    <=    %

       This means, no in-place operators.

       Default  implementations  (described below) are provided for == and the special __tostring
       pseudo-operator. If any other operator is called, Luabind will trigger an error  ("[const]
       class  <type>:  no  <metamethod  name>  defined.",  e.g.  "class  vec:  no  __div operator

       The equality operator (==) has a little hitch; it will not be called if the references are
       equal. This means that the == operator has to do pretty much what's it's expected to do.

       For  Luabind's default == operator, two objects are equal only if they are both objects of
       Luabind-exported classes and have the same addresses, after casting both to a common  base
       if  necessary.  If  they  do  not  have a common base (and are not of the same type), they
       compare unequal.

       Lua does not support operators such as !=, > or >=. That's why you can only  register  the
       operators listed above. When you invoke one of the mentioned operators, lua will define it
       in terms of one of the available operators.

       In the above example the other operand type is  instantiated  by  writing  int().  If  the
       operand type is a complex type that cannot easily be instantiated you can wrap the type in
       a class called other<>. For example:

       To register this class, we don't want  to  instantiate  a  string  just  to  register  the

          struct vec
              vec operator+(std::string);

       Instead we use the other<> wrapper like this:

                  .def(self + other<std::string>())

       To register an application (function call-) operator:

                  .def( self(int()) )

       There's  one special operator. In Lua it's called __tostring, it's not really an operator.
       It is used for converting objects to strings in a standard way in  Lua.  If  you  register
       this  functionality,  you  will  be  able  to use the lua standard function tostring() for
       converting your object to a string.

       To implement this operator in C++ you should supply an operator<< for  std::ostream.  Like
       this example:

          class number {};
          std::ostream& operator<<(std::ostream&, number&);



       If  you  do  not  define a __tostring operator, Luabind supplies a default which result in
       strings of the form [const] <type> object: <address>, i.e.   const  is  prepended  if  the
       object  is  const,  <type>  will be the string you supplied to class_ (or a string derived
       from std::type_info::name for unnamed classes) and <address> will be the  address  of  the
       C++  object.  (Note that in multiple inheritance scenarios where the same object is pushed
       as multiple different base types, the addresses returned for the same most-derived  object
       will differ).

   Nested scopes and static functions
       It  is  possible  to  add nested scopes to a class. This is useful when you need to wrap a
       nested class, or a static function.

                  def("f", &f)

       In this example, f will behave like a static member function of the  class  foo,  and  the
       class nested will behave like a nested class of foo.

       It's also possible to add namespaces to classes using the same syntax.

   Derived classes
       If  you  want  to  register  classes  that  derives  from other classes, you can specify a
       template parameter bases<> to the class_ instantiation. The following hierarchy:

          struct A {};
          struct B : A {};

       Would be registered like this:

              class_<B, A>("B")

       If you have multiple inheritance you can specify more than  one  base.  If  B  would  also
       derive from a class C, it would be registered like this:

              class_<B, bases<A, C> >("B")

       Note that you can omit bases<> when using single inheritance.

          If  you  don't specify that classes derive from each other, luabind will not be able to
          implicitly cast pointers between the types.

   Smart pointers
       When registering a class you can tell luabind to hold all instances explicitly created  in
       Lua in a specific smart pointer type, rather than the default raw pointer. This is done by
       passing an additional template parameter to class_:

          class_<X, P>(…)

       Where the requirements of P are:

                                  │ExpressionReturns           │
                                  │P(raw)         │                   │
                                  │get_pointer(p)Convertible to X* │


       · raw is of type X*

       · p is an instance of P

       get_pointer() overloads are provided for the smart pointers in Boost, and std::auto_ptr<>.
       Should  you  need  to provide your own overload, note that it is called unqualified and is
       expected to be found by argument dependent lookup. Thus it should be defined in  the  same
       namespace as the pointer type it operates on.

       For example:

          class_<X, boost::scoped_ptr<X> >("X")

       Will cause luabind to hold any instance created on the Lua side in a boost::scoped_ptr<X>.
       Note that this doesn't mean all instances will be held by a boost::scoped_ptr<X>. If,  for
       example, you register a function:

          std::auto_ptr<X> make_X();

       the  instance  returned  by  that  will  be  held  in  std::auto_ptr<X>.  This  is handled
       automatically for all smart pointers that implement a get_pointer() overload.

          get_const_holder() has been removed. Automatic  conversions  between  smart_ptr<X>  and
          smart_ptr<X const> no longer work.

          __ok   has  been removed. Similar functionality can be implemented for specific pointer
          types by doing something along the lines of:

              bool is_non_null(std::auto_ptr<X> const& p)
                  return p.get();


              def("is_non_null", &is_non_null)

       When registering a hierarchy of classes, where all instances are to be  held  by  a  smart
       pointer, all the classes should have the baseclass' holder type.  Like this:

              class_<base, boost::shared_ptr<base> >("base")
              class_<derived, base, boost::shared_ptr<base> >("derived")

       Internally, luabind will do the necessary conversions on the raw pointers, which are first
       extracted from the holder type.

       This means that for Luabind a smart_ptr<derived> is not related to a smart_ptr<base>,  but
       derived*  and  base*  are,  as are smart_ptr<derived> and base*. In other words, upcasting
       does not work for smart pointers as target types, but as source types.

   Additional support for shared_ptr and intrusive_ptr
       This limitation cannot be removed for all smart pointers in a generic way, but luabind has
       special support for

          · boost::shared_ptr in shared_ptr_converter.hpp

          · std::shared_ptr in std_shared_ptr_converter.hpp

          · boost::intrusive_ptr in intrusive_ptr_converter.hpp

       You  should  include the header(s) you need in the cpp files which register functions that
       accept  the  corresponding  smart  pointer  types,  to  get  automatic  conversions   from
       smart_ptr<X>  to  smart_ptr<Y>,  whenever  Luabind  would  convert  X* to Y*, removing the
       limitation mentioned above.

       However, the shared_ptr converters might not behave exactly as you would expect:

          1. If the shared_ptr requested (from C++) has the exact same type as the one  which  is
             present in Lua (if any), then a copy will be made.

          2. If  the  pointee  type  of  the  requested  shared_ptr has a shared_from_this member
             (checked automatically at compile time), this will be used to obtain  a  shared_ptr.

                 · If  the  object  is  not  already  held in a shared_ptr, behavior is undefined
                   (probably a bad_weak_ptr exception will be thrown).

                 · If the shared_from_this member is not a  function  with  the  right  prototype
                   (ptr_t shared_from_this() with the expression

                       shared_ptr<RequestedT>(raw->shared_from_this(), raw)

                    being valid, where raw is of type RequestedT* and points to the C++ object in

          3. Otherwise, a new shared_ptr will be created from the raw pointer associated with the
             Lua object (even if it is not held in a shared_ptr). It will have a deleter set that
             holds a strong reference to the Lua object, thus preventing  it’s  collection  until
             the  reference  is released by invoking the deleter (i.e. by resetting or destroying
             the shared_ptr) or until the assocciated lua_State is closed:  then  the  shared_ptr
             becomes dangling.

             If  such a shared_ptr is passed back to Lua, the original Lua object (userdata) will
             be passed instead, preventing the creation of more shared_ptrs with this deleter.

       1. is as you should have expected and 2. is special behavior introduced to avoid  3.  when
       possible.  If you cannot derive your (root) classes from enable_shared_from_this (which is
       the recommended way of providing a shared_from_this method) you must  be  careful  not  to
       close the lua_State when you still have a shared_ptr obtained by 3.

       There are three functions provided to support this (in namespace luabind):

          bool is_state_unreferenced(lua_State* L);

          typedef void(*state_unreferenced_fun)(lua_State* L);
          void set_state_unreferenced_callback(lua_State* L, state_unreferenced_fun cb);
          state_unreferenced_fun get_state_unreferenced_callback(lua_State* L);

       is_state_unreferenced  will  return  false  if  closing  L would make existing shared_ptrs
       dangling and true if it safe (in this respect) to call lua_close(L).

       The cb argument passed to set_state_unreferenced_callback  will  be  called  whenever  the
       return value of is_state_unreferenced(L) would change from false to true.

       get_state_unreferenced_callback returns the current state_unreferenced_fun for L.

       A typical use of this functions would be to replace



          if (luabind::is_state_unreferenced(L))
              luabind::set_state_unreferenced_callback(L, &lua_close);

       (lua_close happens to be a valid state_unreferenced_fun.)

   Unnamed classes
       You can register unnamed classes by not passing a name to class_:


       This  does  not export the class object itself to Lua, meaning that constructors cannot be
       called and enums are only accessible via objects of this class' type.

       This is useful e.g. for registering multiple  instantiations  of  a  class  template,  and
       construct  a  matching  instance  using a factory function, like boost::make_shared of for
       hiding intermediate classes in inheritance hierarchies.

   Splitting class registrations
       In some situations it may be desirable to split a registration of a class across different
       compilation  units.  Partly to save rebuild time when changing in one part of the binding,
       and in some cases compiler limits may force you to split it. To do this  is  very  simple.
       Consider the following sample code:

          void register_part1(class_<X>& x)

          void register_part2(class_<X>& x)

          void register_(lua_State* L)
              class_<X> x("x");


              module(L) [ x ];

       Here,  the  class  X  is  registered  in  two  steps. The two functions register_part1 and
       register_part2 may be put in separate compilation units.

       To  separate  the  module  registration  and   the   classes   to   be   registered,   see


       It is possible to get luabind to handle user defined types like it does the built in types
       by specializing luabind::default_converter<>:

          struct int_wrapper
              int_wrapper(int value)
                : value(value)

              int value;

          namespace luabind
              template <>
              struct default_converter<X>
                : native_converter_base<X>
                  static int compute_score(lua_State* L, int index)
                      return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;

                  X from(lua_State* L, int index)
                      return X(lua_tonumber(L, index));

                  void to(lua_State* L, X const& x)
                      lua_pushnumber(L, x.value);

              template <>
              struct default_converter<X const&>
                : default_converter<X>

       Note that default_converter<> is instantiated for the actual argument and return types  of
       the  bound  functions.  In  the  above  example, we add a specialization for X const& that
       simply forwards to the X converter.  This lets us export functions which accept X by const

       native_converter_base<>  should  be used as the base class for the specialized converters.
       It simplifies the converter interface, and provides  a  mean  for  backward  compatibility
       since the underlying interface is in flux.


       Since  functions  have  to be able to take Lua values (of variable type) we need a wrapper
       around them. This wrapper is called luabind::object. If the function you register takes an
       object, it will match any Lua value. To use it, you need to include <luabind/object.hpp>.

          class object
              template<class T>
              object(lua_State*, T const& value);
              object(from_stack const&);
              object(object const&);


              lua_State* interpreter() const;
              void push() const;
              bool is_valid() const;
              operator safe_bool_type () const;

              template<class Key>
              implementation-defined operator[](Key const&);

              template<class T>
              object& operator=(T const&);
              object& operator=(object const&);

              bool operator==(object const&) const;
              bool operator<(object const&) const;
              bool operator<=(object const&) const;
              bool operator>(object const&) const;
              bool operator>=(object const&) const;
              bool operator!=(object const&) const;

              template <class T>
              implementation-defined operator[](T const& key) const

              void swap(object&);

              implementation-defined operator()();

              template<class A0>
              implementation-defined operator()(A0 const& a0);

              template<class A0, class A1>
              implementation-defined operator()(A0 const& a0, A1 const& a1);

              /* ... */

       When  you  have  a  Lua object, you can assign it a new value with the assignment operator
       (=). When you do this, the default_policy will be used to make  the  conversion  from  C++
       value  to  Lua.  If your luabind::object is a table you can access its members through the
       operator[] or the Iterators. The value returned from the operator[] is a proxy object that
       can be used both for reading and writing values into the table (using operator=).

       Note  that  it  is  impossible  to  know  if a Lua value is indexable or not (lua_gettable
       doesn't fail, it succeeds or crashes). This means that if you're trying to index something
       that  cannot  be  indexed,  you're  on  your own.  Lua will call its panic() function. See

       There are also free functions that can  be  used  for  indexing  the  table,  see  Related

       The  constructor  that  takes  a from_stack object is used when you want to initialize the
       object with a value from the lua stack. The from_stack type has the following constructor:

          from_stack(lua_State* L, int index);

       The index is an ordinary lua stack index, negative values are indexed from the top of  the
       stack. You use it like this:

          object o(from_stack(L, -1));

       This will create the object o and copy the value from the top of the lua stack.

       The interpreter() function returns the Lua state where this object is stored.  If you want
       to manipulate the object with Lua functions directly you can push it onto the Lua stack by
       calling push().

       The operator== will call lua_compare() on the operands and return its result.

       The  is_valid()  function  tells  you whether the object has been initialized or not. When
       created with its default constructor, objects are invalid. To make an  object  valid,  you
       can  assign  it  a  value. If you want to invalidate an object you can simply assign it an
       invalid object.

       The operator safe_bool_type() is equivalent to is_valid(). This means that these  snippets
       are equivalent:

          object o;
          // ...
          if (o)
              // ...


          object o;
          // ...
          if (o.is_valid())
              // ...

       The  application operator will call the value as if it was a function. You can give it any
       number of parameters (currently the default_policy will be used for the  conversion).  The
       returned object refers to the return value (currently only one return value is supported).
       This operator may throw luabind::error if the function call fails. If you want to  specify
       policies  to  your  function call, you can use index-operator (operator[]) on the function
       call, and give the policies within the [ and ]. Like this:

            , 8
            , new my_complex_structure(6)
          ) [ adopt(_3) ];

       This tells luabind to make Lua adopt the ownership  and  responsibility  for  the  pointer
       passed in to the lua-function.

       It's important that all instances of object have been destructed by the time the Lua state
       is closed. The object will keep a pointer to the lua state and release its Lua  object  in
       its destructor.

       Here's an example of how a function can use a table:

          void my_function(object const& table)
              if (type(table) == LUA_TTABLE)
                  table["time"] = std::clock();
                  table["name"] = std::rand() < 500 ? "unusual" : "usual";

                  std::cout << object_cast<std::string>(table[5]) << "\n";

       If  you take a luabind::object as a parameter to a function, any Lua value will match that
       parameter. That's why we have to make sure it's a table before we index into it.

          std::ostream& operator<<(std::ostream&, object const&);

       There's  a  stream  operator  that  makes  it   possible   to   print   objects   or   use
       boost::lexical_cast  to  convert  it  to  a  string. This will use lua's string conversion
       function. So if you convert a C++ object with a tostring operator, the stream operator for
       that type will be used.

       There  are two kinds of iterators. The normal iterator that will use the metamethod of the
       object (if there is any) when the value is  retrieved.  This  iterator  is  simply  called
       luabind::iterator.  The other iterator is called luabind::raw_iterator and will bypass the
       metamethod and give the true contents of the table. They have identical interfaces,  which
       implements the ForwardIterator concept. Apart from the members of standard iterators, they
       have the following members and constructors:

          class iterator
              iterator(object const&);

              object key() const;

              standard iterator members

       The constructor that takes a luabind::object is actually a template that can be used  with
       object.  Passing an object as the parameter to the iterator will construct the iterator to
       refer to the first element in the object.

       The default constructor will initialize the iterator to the one-past-end iterator. This is
       used to test for the end of the sequence.

       The  value type of the iterator is an implementation defined proxy type which supports the
       same operations as luabind::object. Which means that in most cases you can just  treat  it
       as an ordinary object. The difference is that any assignments to this proxy will result in
       the value being inserted at the iterators position, in the table.

       The key() member returns the key used by the iterator when  indexing  the  associated  Lua

       An example using iterators:

          for (iterator i(globals(L)["a"]), end; i != end; ++i)
            *i = 1;

       The  iterator  named end will be constructed using the default constructor and hence refer
       to the end of the sequence. This example will simply  iterate  over  the  entries  in  the
       global table a and set all its values to 1.

   Related functions
       There are a couple of functions related to objects and tables.

          int type(object const&);

       This  function  will  return  the  lua  type  index  of  the given object.  i.e. LUA_TNIL,
       LUA_TNUMBER etc.

          template<class T, class K>
          void settable(object const& o, K const& key, T const& value);
          template<class K>
          object gettable(object const& o, K const& key);
          template<class T, class K>
          void rawset(object const& o, K const& key, T const& value);
          template<class K>
          object rawget(object const& o, K const& key);

       These functions are used for indexing into tables. settable and gettable  translates  into
       calls  to  lua_settable  and lua_gettable respectively. Which means that you could just as
       well use the index operator of the object.

       rawset and rawget will translate into calls to lua_rawset and lua_rawget respectively.  So
       they will bypass any metamethod and give you the true value of the table entry.

          template<class T>
          T object_cast<T>(object const&);
          template<class T, class Policies>
          T object_cast<T>(object const&, Policies);

          template<class T>
          boost::optional<T> object_cast_nothrow<T>(object const&);
          template<class T, class Policies>
          boost::optional<T> object_cast_nothrow<T>(object const&, Policies);

       The  object_cast  function  casts the value of an object to a C++ value.  You can supply a
       policy to handle the conversion from lua to C++. If the cast cannot be made a  cast_failed
       exception   will   be   thrown.   If   you  have  defined  LUABIND_NO_ERROR_CHECKING  (see
       part-build-options) no checking will occur, and if the cast is invalid the application may
       very  well  crash.   The  nothrow versions will return an uninitialized boost::optional<T>
       object, to indicate that the cast could not be performed.

       The function signatures of all of the above functions are really templates for the  object
       parameter,  but  the  intention  is that you should only pass objects in there, that's why
       it's left out of the documentation.

          object globals(lua_State*);
          object registry(lua_State*);

       These functions return the global environment table and the registry table respectively.

          object newtable(lua_State*);

       This function creates a new table and returns it as an object.

          object getmetatable(object const& obj);
          void setmetatable(object const& obj, object const& metatable);

       These functions get and set the metatable of a Lua object.

          lua_CFunction tocfunction(object const& value);
          template <class T> T* touserdata(object const& value)

       These extract values from the object at a lower level than object_cast().

          object getupvalue(object const& function, int index);
          void setupvalue(object const& function, int index, object const& value);

       These get and set the upvalues of function.

   Assigning nil
       To set a table entry to nil, you can use luabind::nil. It will avoid having  to  take  the
       detour  by  first  assigning  nil to an object and then assign that to the table entry. It
       will simply result in a lua_pushnil() call, instead of copying an object.


          using luabind;
          object table = newtable(L);
          table["foo"] = "bar";

          // now, clear the "foo"-field
          table["foo"] = nil;


       In addition to binding C++ functions  and  classes  with  Lua,  luabind  also  provide  an
       OO-system in Lua.

          class 'lua_testclass'

          function lua_testclass:__init(name)
     = name

          function lua_testclass:print()

          a = lua_testclass('example')

       Inheritance can be used between lua-classes:

          class 'derived' (lua_testclass)

          function derived:__init()
              lua_testclass.__init(self, 'derived name')

          function derived:print()
              print('Derived:print() -> ')

       The base class is initialized explicitly by calling its __init() function.

       As  you  can  see  in this example, you can call the base class member functions.  You can
       find all member functions in the base class, but you will have to  give  the  this-pointer
       (self) as first argument.

   Deriving in lua
       It is also possible to derive Lua classes from C++ classes, and override virtual functions
       with Lua functions. To do this we have to create a wrapper class for our C++  base  class.
       This is the class that will hold the Lua object when we instantiate a Lua class.

          class base
              base(const char* s)
              { std::cout << s << "\n"; }

              virtual void f(int a)
              { std::cout << "f(" << a << ")\n"; }

          struct base_wrapper : base, luabind::wrap_base
              base_wrapper(const char* s)
                  : base(s)

              virtual void f(int a)
                  call<void>("f", a);

              static void default_f(base* ptr, int a)
                  return ptr->base::f(a);

          // ...

              class_<base, base_wrapper>("base")
                  .def(constructor<const char*>())
                  .def("f", &base::f, &base_wrapper::default_f)

          Since MSVC6.5 doesn't support explicit template parameters to member functions, instead
          of using the member function call() you call a free function call_member() and pass the
          this-pointer as first parameter.

       Note that if you have both base classes and a base class wrapper, you must give both bases
       and the base class wrapper type as template parameter to class_ (as done  in  the  example
       above).  The order in which you specify them is not important. You must also register both
       the static version and the virtual version of the  function  from  the  wrapper,  this  is
       necessary  in  order to allow luabind to use both dynamic and static dispatch when calling
       the function.

          It is extremely important that the signatures  of  the  static  (default)  function  is
          identical to the virtual function. The fact that one of them is a free function and the
          other a member function doesn't matter, but the parameters as seen from lua must match.
          It  would  not  have  worked  if  the static function took a base_wrapper* as its first
          argument, since the virtual function takes a base* as  its  first  argument  (its  this
          pointer). There's currently no check in luabind to make sure the signatures match.

       If  we  didn't  have a class wrapper, it would not be possible to pass a Lua class back to
       C++. Since the entry points of the virtual functions would still point  to  the  C++  base
       class, and not to the functions defined in Lua. That's why we need one function that calls
       the base class' real function (used if the lua class doesn't redefine it) and one  virtual
       function  that  dispatches  the call into luabind, to allow it to select if a Lua function
       should be called, or if the original function should be called. If  you  don't  intend  to
       derive  from  a  C++  class,  or  if it doesn't have any virtual member functions, you can
       register it without a class wrapper.

       You don't need to have a class wrapper in order to derive from a  class,  but  if  it  has
       virtual functions you may have silent errors.

       The  wrappers  must  derive from luabind::wrap_base, it contains a Lua reference that will
       hold the Lua instance of the object to make it possible to dispatch virtual function calls
       into Lua. This is done through an overloaded member function:

          template<class Ret>
          Ret call(char const* name, ...)

       Its  used  in  a  similar  way as call_function, with the exception that it doesn't take a
       lua_State pointer, and the name is a member function in the Lua class.

          The current implementation of call_member is  not  able  to  distinguish  const  member
          functions  from non-const. If you have a situation where you have an overloaded virtual
          function where the only difference in their signatures is their  constness,  the  wrong
          overload will be called by call_member. This is rarely the case though.

          You  can  also  override  virtual  member  functions  per instance which often makes it
          unnecessary to derive a new class in Lua. Instead of e.g.

              class "D" (B)

              function D:__init() B.__init(self) end
              function D:virtual_function() ... end

          you may be able to get around with

              b = B()
              function b:virtual_function() ... end

   Object identity
       When a pointer or reference to a registered class with a wrapper is passed to Lua, luabind
       will  query  for  it's  dynamic  type. If the dynamic type inherits from wrap_base, object
       identity is preserved.

          struct A { .. };
          struct A_wrap : A, wrap_base { .. };

          A* f(A* ptr) { return ptr; }

              class_<A, A_wrap>("A"),
              def("f", &f)

          > class 'B' (A)
          > x = B()
          > assert(x == f(x)) -- object identity is preserved when object is
                              -- passed through C++

       This functionality relies on RTTI being enabled (that LUABIND_NO_RTTI is not defined).

   Overloading operators
       You can overload most operators in Lua for your classes. You do this by simply declaring a
       member  function  with  the same name as an operator (the name of the metamethods in Lua).
       The operators you can overload are:

          · __add

          · __sub

          · __mul

          · __div

          · __pow

          · __lt

          · __le

          · __eq

          · __call

          · __unm

          · __tostring

          · __len

       __tostring isn't really an operator, but  it's  the  metamethod  that  is  called  by  the
       standard  library's  tostring()  function.  There's  one strange behavior regarding binary
       operators. You are not guaranteed that the self pointer you  get  actually  refers  to  an
       instance  of  your  class. This is because Lua doesn't distinguish the two cases where you
       get the other operand as left hand value or  right  hand  value.  Consider  the  following

          class 'my_class'

            function my_class:__init(v)
                self.val = v

            function my_class:__sub(v)
                return my_class(self.val - v.val)

            function my_class:__tostring()
                return self.val

       This  will  work well as long as you only subtracts instances of my_class with each other.
       But If you want to be able to subtract ordinary numbers from your class too, you  have  to
       manually check the type of both operands, including the self object.

          function my_class:__sub(v)
              if (type(self) == 'number') then
                  return my_class(self - v.val)

              elseif (type(v) == 'number') then
                  return my_class(self.val - v)

                  -- assume both operands are instances of my_class
                  return my_class(self.val - v.val)


       The  reason why __sub is used as an example is because subtraction is not commutative (the
       order of the operands matters). That's why luabind cannot change order of the operands  to
       make the self reference always refer to the actual class instance.

       If  you  have  two  different Lua classes with an overloaded operator, the operator of the
       right hand side type will be called. If the other operand is a C++  class  with  the  same
       operator  overloaded,  it will be prioritized over the Lua class' operator. If none of the
       C++ overloads matches, the Lua class operator will be called.

       If an object needs to perform actions when it's collected we provide a __finalize function
       that  can  be  overridden  in  lua-classes. The __finalize functions will be called on all
       classes in the inheritance chain, starting with the most derived type.


          function lua_testclass:__finalize()
              -- called when the an object is collected

       If your lua C++ classes don't have wrappers (see Deriving in lua) and you derive from them
       in  lua,  they may be sliced. Meaning, if an object is passed into C++ as a pointer to its
       base class, the lua part will be separated from the C++ base part. This means that if  you
       call  virtual  functions on that C++ object, they will not be dispatched to the lua class.
       It also means that if you adopt the object, the lua part will be garbage collected.

          | C++ object         |    <- ownership of this part is transferred
          |                    |       to c++ when adopted
          | lua class instance |    <- this part is garbage collected when
          | and lua members    |       instance is adopted, since it cannot
          +--------------------+       be held by c++.

       The problem can be illustrated by this example:

          struct A {};

          A* filter_a(A* a) { return a; }
          void adopt_a(A* a) { delete a; }

          using namespace luabind;

              def("filter_a", &filter_a),
              def("adopt_a", &adopt_a, adopt(_1))

       In lua:

          a = A()
          b = filter_a(a)

       In this example, lua cannot know that b actually is the same object  as  a,  and  it  will
       therefore  consider  the  object  to be owned by the C++ side.  When the b pointer then is
       adopted, a runtime error will be raised because an  object  not  owned  by  lua  is  being
       adopted to C++.

       If you have a wrapper for your class, none of this will happen, see Object identity.


       If  any of the functions you register throws an exception when called, that exception will
       be caught by luabind and converted to an error string and lua_error() will be invoked.  If
       the  exception  is  a std::exception or a const char* the string that is pushed on the Lua
       stack, as error message, will be the string  returned  by  std::exception::what()  or  the
       string  itself respectively. If the exception is unknown, a generic string saying that the
       function threw an exception will be pushed.

       If you have an exception type that isn't derived  from  std::exception,  or  you  wish  to
       change  the  error  message  from the default result of what(), it is possible to register
       custom exception handlers:

          struct my_exception

          void translate_my_exception(lua_State* L, my_exception const&)
              lua_pushstring(L, "my_exception");



       translate_my_exception() will be called by luabind  whenever  a  my_exception  is  caught.
       lua_error()  will be called after the handler function returns, so it is expected that the
       function will push an error string on the stack.

       Any function that invokes Lua code may throw luabind::error. This exception means  that  a
       Lua  run-time  error  occurred.  The  error  message is found on top of the Lua stack. The
       reason why the exception doesn't contain the error string itself is because it would  then
       require heap allocation which may fail. If an exception class throws an exception while it
       is being thrown itself, the application will be terminated.

       Error's synopsis is:

          class error : public std::exception
              lua_State* state() const throw();
              virtual const char* what() const throw();

       The state function returns a pointer to the Lua state in which the error was thrown.  This
       pointer  may  be invalid if you catch this exception after the lua state is destructed. If
       the Lua state is valid you can use it to retrieve the error message from the  top  of  the
       Lua stack.

       An example of where the Lua state pointer may point to an invalid state follows:

          struct lua_state
              lua_state(lua_State* L): m_L(L) {}
              ~lua_state() { lua_close(m_L); }
              operator lua_State*() { return m_L; }
              lua_State* m_L;

          int main()
                  lua_state L = luaL_newstate();
                  /* ... */
              catch(luabind::error& e)
                  lua_State* L = e.state();
                  // L will now point to the destructed
                  // Lua state and be invalid
                  /* ... */

       There's  another exception that luabind may throw: luabind::cast_failed, this exception is
       thrown from call_function<> or call_member<>. It means that the return value from the  Lua
       function couldn't be converted to a C++ value. It is also thrown from object_cast<> if the
       cast cannot be made.

       The synopsis for luabind::cast_failed is:

          class cast_failed : public std::exception
              lua_State* state() const throw();
              LUABIND_TYPE_INFO info() const throw();
              virtual const char* what() const throw();

       Again, the state member function returns a pointer  to  the  Lua  state  where  the  error
       occurred. See the example above to see where this pointer may be invalid.

       The  info  member function returns the user defined LUABIND_TYPE_INFO, which defaults to a
       const std::type_info*. This type info describes the type that we tried to cast a Lua value

       If you have defined LUABIND_NO_EXCEPTIONS none of these exceptions will be thrown, instead
       you can set two callback functions that are called instead.  These two functions are  only
       defined if LUABIND_NO_EXCEPTIONS are defined.


       The  function  you set will be called when a runtime-error occur in Lua code. You can find
       an error message on top of the Lua stack. This function is not expected to return,  if  it
       does luabind will call std::terminate().

          luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))

       The  function  you  set  is  called  instead of throwing cast_failed. This function is not
       expected to return, if it does luabind will call std::terminate().


       Sometimes it is necessary to control how luabind passes arguments and return value, to  do
       this we have policies. All policies use an index to associate them with an argument in the
       function signature. These indices are result and _N (where N  >=  1).  When  dealing  with
       member functions _1 refers to the this pointer.

   Policies currently implemented
       · adopt

       · dependency

       · out_value

       · pure_out_value

       · return_reference_to

       · copy

       · discard_result

       · return_stl_iterator

       · raw

       · yield

       Used to transfer ownership across language boundaries.

   Defined in
          #include <luabind/adopt_policy.hpp>


                             │Parameter │ Purpose                          │
                             │index     │ The  index which should transfer │
                             │          │ ownership, _N or result          │

          X* create()
              return new X;

              def("create", &create, adopt(result))

       The dependency policy is used to create life-time dependencies between  values.   This  is
       needed for example when returning internal references to some class.

   Defined in
          #include <luabind/dependency_policy.hpp>

          dependency(nurse_index, patient_index)

                            Parameter       Purpose
                            nurse_index     The  index  which  will keep the
                                            patient alive.
                            patient_index   The index  which  will  be  kept
                           │              │                                  │
   Example                 │              │                                  │
          struct X         │              │                                  │
          {                │              │                                  │
              B member;    │              │                                  │
Binary file (standard input) matches