.\" Man page generated from reStructuredText. . .TH "LUABIND" "3" "Apr 23, 2020" "0.9" "Luabind" .SH NAME luabind \- Luabind Documentation . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .sp This is the documentation for Luabind 0.9.1d1 \&. .sp 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. .sp The old official homepage can be found at \fI\%http://www.rasterbar.com/products/luabind.html\fP\&. .sp Contents: .SH INTRODUCTION .sp 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. .sp It is implemented utilizing template meta programming. That means that you don\(aqt need an extra preprocess pass to compile your project (it is done by the compiler). It also means you don\(aqt (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. .sp Luabind is released under the terms of the \fI\%MIT license\fP\&. .sp We are very interested in hearing about projects that use luabind, please let us know about your project. .sp The main channel for help and feedback is the \fI\%luabind mailing list\fP\&. There\(aqs also an IRC channel \fB#luabind\fP on irc.freenode.net. .sp Additionally, this fork’s \fI\%github issue tracker\fP can also be used for bug reports, feature requests and questions. .SH FEATURES .sp Luabind supports: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Overloaded free functions .IP \(bu 2 C++ classes in Lua .IP \(bu 2 Overloaded member functions .IP \(bu 2 Operators .IP \(bu 2 Properties .IP \(bu 2 Enums (also C++11 \fBenum class\fP if available) .IP \(bu 2 Lua functions in C++ .IP \(bu 2 Lua classes in C++ .IP \(bu 2 Lua classes (single inheritance) .IP \(bu 2 Derives from Lua or C++ classes .IP \(bu 2 Override virtual functions from C++ classes .IP \(bu 2 Implicit casts between registered types .IP \(bu 2 Best match signature matching .IP \(bu 2 Return value policies and parameter policies .UNINDENT .UNINDENT .UNINDENT .SH PORTABILITY .sp Luabind is currently tested regularly with .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Microsoft Visual C++ 11 (2012) x32 and x64 .IP \(bu 2 gcc 4.8 x64 (with and without \-std=c++11) .IP \(bu 2 Clang 3.2 x64 (with and without \-std=c++11) .UNINDENT .UNINDENT .UNINDENT .sp 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 \fI\%github issue tracker\fP\&. .SH BUILDING LUABIND .SS Prerequisites .sp Apart from Lua 5.1 or (recommended) 5.2, Luabind depends on a number of Boost libraries. It also depends on \fI\%CMake\fP to build the library and run the tests. .SS Windows .sp 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. .sp The same applies to Boost and the BOOST_ROOT environment variable. .SS Linux and other *nix flavors .sp 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 \fBLUA_DIR\fP to point to the installation prefix. .sp \fBBOOST_ROOT\fP 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. .SS Building and testing .sp 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 MSVC). .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 To build your application against the shared library variant, LUABIND_DYNAMIC_LINK needs to be defined to properly import symbols. .UNINDENT .UNINDENT .sp To run the unit tests, invoke your build tool with the test target, e.g. \fBmake test\fP on Unix or \fBnmake test/msbuild RUN_TESTS.vcxproj\fP for MSVC. This run the (previously built) unit tests in the current variant. A clean test run output should end with something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 100% tests passed, 0 tests failed out of 51 Total Test time (real) = 1.23 sec .ft P .fi .UNINDENT .UNINDENT .sp A failed run would end with something like: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 98% tests passed, 1 tests failed out of 51 Total Test time (real) = 1.23 sec The following tests FAILED: 1 \- abstract_base (Failed) .ft P .fi .UNINDENT .UNINDENT .SH BASIC USAGE .sp To use luabind, you must include \fBlua.h\fP and luabind\(aqs main header file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C extern "C" { #include "lua.h" } #include .ft P .fi .UNINDENT .UNINDENT .sp This includes support for both registering classes and functions. If you just want to have support for functions or classes you can include \fBluabind/function.hpp\fP and \fBluabind/class.hpp\fP separately: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include #include .ft P .fi .UNINDENT .UNINDENT .sp The first thing you need to do is to call \fBluabind::open(lua_State*)\fP which will register the functions to create classes from Lua, and initialize some state\-global structures used by luabind. If you don\(aqt 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\(aqt 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. .sp Luabind\(aqs headers will never include \fBlua.h\fP directly, but through \fB\fP\&. If you for some reason need to include another Lua header, you can modify this file. .SS Hello world .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include #include void greet() { std::cout << "hello world!\en"; } extern "C" int init(lua_State* L) { using namespace luabind; open(L); module(L) [ def("greet", &greet) ]; return 0; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Lua 5.0 Copyright (C) 1994\-2003 Tecgraf, PUC\-Rio > loadlib(\(aqhello_world.dll\(aq, \(aqinit\(aq)() > greet() Hello world! > .ft P .fi .UNINDENT .UNINDENT .SH SCOPES .sp 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 \fBluabind::module\fP class is used. It is used like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ // declarations ]; .ft P .fi .UNINDENT .UNINDENT .sp This will register all declared functions or classes in the global namespace in Lua. .sp You can also register into a custom Lua table wrapped in a part\-object: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object mod = newtable(L); module(L, mod) [ // declarations ]; .ft P .fi .UNINDENT .UNINDENT .sp You can then directly use all object manipulation functions on \fBmod\fP\&. .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L, "my_library") [ // declarations ]; .ft P .fi .UNINDENT .UNINDENT .sp Here all declarations will be put in the my_library table. .sp If you want nested namespace\(aqs you can use the \fBluabind::namespace_\fP class. It works exactly as \fBluabind::module\fP except that it doesn\(aqt take a lua_State* in it\(aqs constructor. An example of its usage could look like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L, "my_library") [ // declarations namespace_("detail") [ // library\-private declarations ] ]; .ft P .fi .UNINDENT .UNINDENT .sp As you might have figured out, the following declarations are equivalent: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ namespace_("my_library") [ // declarations ] ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L, "my_library") [ // declarations ]; .ft P .fi .UNINDENT .UNINDENT .sp Each declaration must be separated by a comma, like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("f", &f), def("g", &g), class_("A") .def(constructor), def("h", &h) ]; .ft P .fi .UNINDENT .UNINDENT .sp More about the actual declarations in the part\-functions and part\-classes sections. .SH BINDING FUNCTIONS TO LUA .sp To bind functions to Lua you use the function \fBluabind::def()\fP\&. It has the following synopsis: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template void def(const char* name, F f, const Policies&); .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP \(bu 2 name is the name the function will have within Lua. .IP \(bu 2 F is the function pointer you want to register. .IP \(bu 2 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 section. .UNINDENT .sp An example usage could be if you want to register the function \fBfloat std::sin(float)\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("sin", &std::sin) ]; .ft P .fi .UNINDENT .UNINDENT .SS Overloaded functions .sp 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, \fBint f(const char*)\fP and \fBvoid f(int)\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("f", (int(*)(const char*)) &f), def("f", (void(*)(int)) &f) ]; .ft P .fi .UNINDENT .UNINDENT .SS Signature matching .sp luabind will generate code that checks the Lua stack to see if the values there can match your functions\(aq 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\(aqs 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\(aqt distinguish between floats and integers, both will always match. .sp 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\(aqt. .SS Ownership transfer .sp To correctly handle ownership transfer, create_a() would need an adopt return value policy. More on this in the part\-policies section. .sp For example, if the following function and class is registered: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { void f(); void f() const; }; const A* create_a(); struct B: A {}; struct C: B {}; void g(A*); void g(B*); .ft P .fi .UNINDENT .UNINDENT .sp And the following Lua code is executed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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*) .ft P .fi .UNINDENT .UNINDENT .SS Calling Lua functions .sp To call a Lua function, you can either use \fBcall_function()\fP or an \fBobject\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template Ret call_function(lua_State* L, const char* name, ...) template Ret call_function(object const& obj, ...) .ft P .fi .UNINDENT .UNINDENT .sp There are two overloads of the \fBcall_function\fP 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 function. .sp 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 \fBluabind::error\fP if the function call fails. .sp The return value isn\(aqt 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int ret = call_function( L , "a_lua_function" , new complex_class() )[ adopt(_1) ]; .ft P .fi .UNINDENT .UNINDENT .sp If you want to pass a parameter as a reference, you have to wrap it with the \fI\%Boost.Ref\fP\&. .sp Like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int ret = call_function(L, "fun", boost::ref(val)); .ft P .fi .UNINDENT .UNINDENT .sp If you want to use a custom error handler for the function call, see \fBset_pcall_callback\fP under sec\-pcall\-errorfunc\&. .SS Using Lua threads .sp To start a Lua thread, you have to call \fBlua_resume()\fP, this means that you cannot use the previous function \fBcall_function()\fP to start a thread. You have to use .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template Ret resume_function(lua_State* L, const char* name, ...) template Ret resume_function(object const& obj, ...) .ft P .fi .UNINDENT .UNINDENT .sp and .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template Ret resume(lua_State* L, ...) .ft P .fi .UNINDENT .UNINDENT .sp The first time you start the thread, you have to give it a function to execute. i.e. you have to use \fBresume_function\fP, when the Lua function yields, it will return the first value passed in to \fBlua_yield()\fP\&. When you want to continue the execution, you just call \fBresume()\fP on your \fBlua_State\fP, since it\(aqs already executing a function, you don\(aqt pass it one. The parameters to \fBresume()\fP will be returned by \fByield()\fP on the Lua side. .sp 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. .sp With the overload of \fBresume_function\fP that takes an part\-object, it is important that the object was constructed with the thread as its \fBlua_State*\fP\&. Like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C lua_State* thread = lua_newthread(L); object fun = get_global(\fBthread\fP)["my_thread_fun"]; resume_function(fun); .ft P .fi .UNINDENT .UNINDENT .SS Binding function objects with explicit signatures .sp Using \fBluabind::tag_function<>\fP it is possible to export function objects from which luabind can\(aqt automatically deduce a signature. This can be used to slightly alter the signature of a bound function, or even to bind stateful function objects. .sp Synopsis: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template \fIimplementation\-defined\fP tag_function(F f); .ft P .fi .UNINDENT .UNINDENT .sp Where \fBSignature\fP is a function type describing the signature of \fBF\fP\&. It can be used like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int f(int x); // alter the signature so that the return value is ignored def("f", tag_function(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(plus(3))); .ft P .fi .UNINDENT .UNINDENT .SH BINDING CLASSES TO LUA .sp To register classes you use a class called \fBclass_\fP\&. Its name is supposed to resemble the C++ keyword, to make it look more intuitive. It has an overloaded member function \fBdef()\fP 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. .sp Let\(aqs start with a simple example. Consider the following C++ class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class testclass { public: testclass(const std::string& s): m_string(s) {} void print_string() { std::cout << m_string << "\en"; } private: std::string m_string; }; .ft P .fi .UNINDENT .UNINDENT .sp To register it with a Lua environment, write as follows (assuming you are using namespace luabind): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("testclass") .def(constructor()) .def("print_string", &testclass::print_string) ]; .ft P .fi .UNINDENT .UNINDENT .sp This will register the class with the name testclass and constructor that takes a string as argument and one member function with the name \fBprint_string\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Lua 5.0 Copyright (C) 1994\-2003 Tecgraf, PUC\-Rio > a = testclass(\(aqa string\(aq) > a:print_string() a string .ft P .fi .UNINDENT .UNINDENT .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { int a; }; int plus(A* o, int v) { return o\->a + v; } .ft P .fi .UNINDENT .UNINDENT .sp You can register \fBplus()\fP as if it was a member function of A like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_("A") .def("plus", &plus) .ft P .fi .UNINDENT .UNINDENT .sp \fBplus()\fP 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). .SS Overloaded member functions .sp 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 \fBdef\fP\&. 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\(aqs a short tutorial (for more info, refer to your favorite book on C++). .sp The syntax for member function pointer follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \fIreturn\-value\fP (\fIclass\-name\fP::*)(\fIarg1\-type\fP, \fIarg2\-type\fP, \fI\&...\fP) .ft P .fi .UNINDENT .UNINDENT .sp Here\(aqs an example illlustrating this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { void f(int); void f(int, int); }; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_() .def("f", (void(A::*)(int))&A::f) .ft P .fi .UNINDENT .UNINDENT .sp This selects the first overload of the function \fBf\fP to bind. The second overload is not bound. .SS Properties .sp To register a global data member with a class is easily done. Consider the following class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { int a; }; .ft P .fi .UNINDENT .UNINDENT .sp This class is registered like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A") .def_readwrite("a", &A::a) ]; .ft P .fi .UNINDENT .UNINDENT .sp This gives read and write access to the member variable \fBA::a\fP\&. It is also possible to register attributes with read\-only access: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A") .def_readonly("a", &A::a) ]; .ft P .fi .UNINDENT .UNINDENT .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { int m; }; struct B { A a; }; .ft P .fi .UNINDENT .UNINDENT .sp When binding \fBB\fP to lua, the following expression code should work: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C b = B() b.a.m = 1 assert(b.a.m == 1) .ft P .fi .UNINDENT .UNINDENT .sp This requires the first lookup (on \fBa\fP) to return a reference to \fBA\fP, 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. .sp You can also register getter and setter functions and make them look as if they were a public data member. Consider the following class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class A { public: void set_a(int x) { a = x; } int get_a() const { return a; } private: int a; }; .ft P .fi .UNINDENT .UNINDENT .sp It can be registered as if it had a public data member a like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_("A") .property("a", &A::get_a, &A::set_a) .ft P .fi .UNINDENT .UNINDENT .sp This way the \fBget_a()\fP and \fBset_a()\fP 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 \fBhas to be const\fP, otherwise it won\(aqt compile. This seems to be a common source of errors. .SS Enums .sp 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 this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A") .enum_("constants") [ value("my_enum", 4), value("my_2nd_enum", 7), value("another_enum", 6) ] ]; .ft P .fi .UNINDENT .UNINDENT .sp 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Lua 5.0 Copyright (C) 1994\-2003 Tecgraf, PUC\-Rio > print(A.my_enum) 4 > print(A.another_enum) 6 .ft P .fi .UNINDENT .UNINDENT .SS Operators .sp To bind operators you have to include \fB\fP\&. .sp The mechanism for registering operators on your class is pretty simple. You use a global name \fBluabind::self\fP to refer to the class itself and then you just write the operator expression inside the \fBdef()\fP call. This class: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct vec { vec operator+(int s); }; .ft P .fi .UNINDENT .UNINDENT .sp Is registered like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("vec") .def(\fBself + int()\fP) ]; .ft P .fi .UNINDENT .UNINDENT .sp This will work regardless if your plus operator is defined inside your class or as a free function. .sp If your operator is const (or, when defined as a free function, takes a const reference to the class itself) you have to use \fBconst_self\fP instead of \fBself\fP\&. Like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("vec") .def(\fBconst_self\fP + int()) ]; .ft P .fi .UNINDENT .UNINDENT .sp The operators supported are those available in Lua: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C + \- * / == < <= % .ft P .fi .UNINDENT .UNINDENT .sp This means, no in\-place operators. .sp Default implementations (described below) are provided for \fI==\fP and the special \fI__tostring\fP pseudo\-operator. If any other operator is called, Luabind will trigger an error ("[const] class : no defined.", e.g. "class vec: no __div operator defined."). .sp The equality operator (\fB==\fP) has a little hitch; it will not be called if the references are equal. This means that the \fB==\fP operator has to do pretty much what\(aqs it\(aqs expected to do. .sp For Luabind\(aqs default \fI==\fP 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. .sp Lua does not support operators such as \fB!=\fP, \fB>\fP or \fB>=\fP\&. That\(aqs 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. .sp In the above example the other operand type is instantiated by writing \fBint()\fP\&. If the operand type is a complex type that cannot easily be instantiated you can wrap the type in a class called \fBother<>\fP\&. For example: .sp To register this class, we don\(aqt want to instantiate a string just to register the operator. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct vec { vec operator+(std::string); }; .ft P .fi .UNINDENT .UNINDENT .sp Instead we use the \fBother<>\fP wrapper like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("vec") .def(self + \fBother()\fP) ]; .ft P .fi .UNINDENT .UNINDENT .sp To register an application (function call\-) operator: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("vec") .def( \fBself(int())\fP ) ]; .ft P .fi .UNINDENT .UNINDENT .sp There\(aqs one special operator. In Lua it\(aqs called \fB__tostring\fP, it\(aqs 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 \fBtostring()\fP for converting your object to a string. .sp To implement this operator in C++ you should supply an \fBoperator<<\fP for std::ostream. Like this example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class number {}; std::ostream& operator<<(std::ostream&, number&); \&... module(L) [ class_("number") .def(\fBtostring(self)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .sp If you do not define a \fB__tostring\fP operator, Luabind supplies a default which result in strings of the form \fB[const] object:
\fP, i.e. \fBconst\fP is prepended if the object is const, \fB\fP will be the string you supplied to \fBclass_\fP (or a string derived from \fIstd::type_info::name\fP for unnamed classes) and \fB
\fP 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). .SS Nested scopes and static functions .sp 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_("foo") .def(constructor<>()) \fB\&.scope [ class_("nested"), def("f", &f) ]\fP; .ft P .fi .UNINDENT .UNINDENT .sp In this example, \fBf\fP will behave like a static member function of the class \fBfoo\fP, and the class \fBnested\fP will behave like a nested class of \fBfoo\fP\&. .sp It\(aqs also possible to add namespaces to classes using the same syntax. .SS Derived classes .sp If you want to register classes that derives from other classes, you can specify a template parameter \fBbases<>\fP to the \fBclass_\fP instantiation. The following hierarchy: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A {}; struct B : A {}; .ft P .fi .UNINDENT .UNINDENT .sp Would be registered like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A"), class_("B") ]; .ft P .fi .UNINDENT .UNINDENT .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_ >("B") ]; .ft P .fi .UNINDENT .UNINDENT .sp Note that you can omit \fBbases<>\fP when using single inheritance. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 If you don\(aqt specify that classes derive from each other, luabind will not be able to implicitly cast pointers between the types. .UNINDENT .UNINDENT .SS Smart pointers .sp 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 \fBclass_\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_(…) .ft P .fi .UNINDENT .UNINDENT .sp Where the requirements of \fBP\fP are: .TS center; |l|l|. _ T{ Expression T} T{ Returns T} _ T{ \fBP(raw)\fP T} T{ T} _ T{ \fBget_pointer(p)\fP T} T{ Convertible to \fBX*\fP T} _ .TE .sp where: .INDENT 0.0 .IP \(bu 2 \fBraw\fP is of type \fBX*\fP .IP \(bu 2 \fBp\fP is an instance of \fBP\fP .UNINDENT .sp \fBget_pointer()\fP overloads are provided for the smart pointers in Boost, and \fBstd::auto_ptr<>\fP\&. Should you need to provide your own overload, note that it is called unqualified and is expected to be found by \fIargument dependent lookup\fP\&. Thus it should be defined in the same namespace as the pointer type it operates on. .sp For example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_\fP >("X") .def(constructor<>()) .ft P .fi .UNINDENT .UNINDENT .sp Will cause luabind to hold any instance created on the Lua side in a \fBboost::scoped_ptr\fP\&. Note that this doesn\(aqt mean \fBall\fP instances will be held by a \fBboost::scoped_ptr\fP\&. If, for example, you register a function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C std::auto_ptr make_X(); .ft P .fi .UNINDENT .UNINDENT .sp the instance returned by that will be held in \fBstd::auto_ptr\fP\&. This is handled automatically for all smart pointers that implement a \fBget_pointer()\fP overload. .sp \fBIMPORTANT:\fP .INDENT 0.0 .INDENT 3.5 \fBget_const_holder()\fP has been removed. Automatic conversions between \fBsmart_ptr\fP and \fBsmart_ptr\fP no longer work. .UNINDENT .UNINDENT .sp \fBIMPORTANT:\fP .INDENT 0.0 .INDENT 3.5 \fB__ok\fP has been removed. Similar functionality can be implemented for specific pointer types by doing something along the lines of: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C bool is_non_null(std::auto_ptr const& p) { return p.get(); } … def("is_non_null", &is_non_null) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .UNINDENT .sp When registering a hierarchy of classes, where all instances are to be held by a smart pointer, all the classes should have the baseclass\(aq holder type. Like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_ >("base") .def(constructor<>()), class_\fP >("derived") .def(constructor<>()) ]; .ft P .fi .UNINDENT .UNINDENT .sp Internally, luabind will do the necessary conversions on the raw pointers, which are first extracted from the holder type. .sp This means that for Luabind a \fBsmart_ptr\fP is not related to a \fBsmart_ptr\fP, but \fBderived*\fP and \fBbase*\fP are, as are \fBsmart_ptr\fP and \fBbase*\fP\&. In other words, upcasting does not work for smart pointers as target types, but as source types. .SS Additional support for shared_ptr and intrusive_ptr .sp This limitation cannot be removed for all smart pointers in a generic way, but luabind has special support for .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fBboost::shared_ptr\fP in \fBshared_ptr_converter.hpp\fP .IP \(bu 2 \fBstd::shared_ptr\fP in \fBstd_shared_ptr_converter.hpp\fP .IP \(bu 2 \fBboost::intrusive_ptr\fP in \fBintrusive_ptr_converter.hpp\fP .UNINDENT .UNINDENT .UNINDENT .sp 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 \fBsmart_ptr\fP to \fBsmart_ptr\fP, whenever Luabind would convert \fBX*\fP to \fBY*\fP, removing the limitation mentioned above. .sp However, the \fBshared_ptr\fP converters might not behave exactly as you would expect: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP 1. 3 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. .IP 2. 3 If the pointee type of the requested shared_ptr has a \fBshared_from_this\fP member (checked automatically at compile time), this will be used to obtain a \fBshared_ptr\fP\&. Caveats: .INDENT 3.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 If the object is not already held in a shared_ptr, behavior is undefined (probably a \fBbad_weak_ptr\fP exception will be thrown). .IP \(bu 2 If the \fBshared_from_this\fP member is not a function with the right prototype (\fBptr_t shared_from_this()\fP with the expression .INDENT 3.0 .INDENT 3.5 .sp .nf .ft C shared_ptr(raw\->shared_from_this(), raw) .ft P .fi .UNINDENT .UNINDENT .sp being valid, where \fBraw\fP is of type \fBRequestedT*\fP and points to the C++ object in Lua. .UNINDENT .UNINDENT .UNINDENT .IP 3. 3 Otherwise, a new \fBshared_ptr\fP will be created from the raw pointer associated with the Lua object (even if it is not held in a \fBshared_ptr\fP). 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 \fBshared_ptr\fP) or until the assocciated \fBlua_State\fP is closed: then the \fBshared_ptr\fP becomes dangling. .sp If such a \fBshared_ptr\fP is passed back to Lua, the original Lua object (userdata) will be passed instead, preventing the creation of more \fBshared_ptr\fPs with this deleter. .UNINDENT .UNINDENT .UNINDENT .sp 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 \fBenable_shared_from_this\fP (which is the recommended way of providing a \fBshared_from_this\fP method) you must be careful not to close the \fBlua_State\fP when you still have a \fBshared_ptr\fP obtained by 3. .sp There are three functions provided to support this (in namespace luabind): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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); .ft P .fi .UNINDENT .UNINDENT .sp \fBis_state_unreferenced\fP will return \fBfalse\fP if closing \fBL\fP would make existing \fBshared_ptrs\fP dangling and \fBtrue\fP if it safe (in this respect) to call \fBlua_close(L)\fP\&. .sp The \fBcb\fP argument passed to \fBset_state_unreferenced_callback\fP will be called whenever the return value of \fBis_state_unreferenced(L)\fP would change from \fBfalse\fP to \fBtrue\fP\&. .sp \fBget_state_unreferenced_callback\fP returns the current \fBstate_unreferenced_fun\fP for \fBL\fP\&. .sp A typical use of this functions would be to replace .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C lua_close(L); .ft P .fi .UNINDENT .UNINDENT .sp with .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C if (luabind::is_state_unreferenced(L)) lua_close(L); else luabind::set_state_unreferenced_callback(L, &lua_close); .ft P .fi .UNINDENT .UNINDENT .sp (\fBlua_close\fP happens to be a valid \fBstate_unreferenced_fun\fP\&.) .SS Unnamed classes .sp You can register unnamed classes by not passing a name to \fBclass_\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class_() .ft P .fi .UNINDENT .UNINDENT .sp 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\(aq type. .sp 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. .SS Splitting class registrations .sp 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void register_part1(class_& x) { x.def(/*...*/); } void register_part2(class_& x) { x.def(/*...*/); } void register_(lua_State* L) { class_ x("x"); register_part1(x); register_part2(x); module(L) [ x ]; } .ft P .fi .UNINDENT .UNINDENT .sp Here, the class \fBX\fP is registered in two steps. The two functions \fBregister_part1\fP and \fBregister_part2\fP may be put in separate compilation units. .sp To separate the module registration and the classes to be registered, see part\-split\-registration\&. .SH ADDING CONVERTERS FOR USER DEFINED TYPES .sp It is possible to get luabind to handle user defined types like it does the built in types by specializing \fBluabind::default_converter<>\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct int_wrapper { int_wrapper(int value) : value(value) {} int value; }; namespace luabind { template <> struct default_converter : native_converter_base { 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 : default_converter {}; } .ft P .fi .UNINDENT .UNINDENT .sp Note that \fBdefault_converter<>\fP is instantiated for the actual argument and return types of the bound functions. In the above example, we add a specialization for \fBX const&\fP that simply forwards to the \fBX\fP converter. This lets us export functions which accept \fBX\fP by const reference. .sp \fBnative_converter_base<>\fP 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. .SH OBJECT .sp Since functions have to be able to take Lua values (of variable type) we need a wrapper around them. This wrapper is called \fBluabind::object\fP\&. If the function you register takes an object, it will match any Lua value. To use it, you need to include \fB\fP\&. .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class object { public: template object(lua_State*, T const& value); object(from_stack const&); object(object const&); object(); ~object(); lua_State* interpreter() const; void push() const; bool is_valid() const; operator \fIsafe_bool_type\fP () const; template \fIimplementation\-defined\fP operator[](Key const&); template 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 \fIimplementation\-defined\fP operator[](T const& key) const void swap(object&); \fIimplementation\-defined\fP operator()(); template \fIimplementation\-defined\fP operator()(A0 const& a0); template \fIimplementation\-defined\fP operator()(A0 const& a0, A1 const& a1); /* ... */ }; .ft P .fi .UNINDENT .UNINDENT .sp When you have a Lua object, you can assign it a new value with the assignment operator (=). When you do this, the \fBdefault_policy\fP will be used to make the conversion from C++ value to Lua. If your \fBluabind::object\fP is a table you can access its members through the operator[] or the \fI\%Iterators\fP\&. 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=). .sp Note that it is impossible to know if a Lua value is indexable or not (\fBlua_gettable\fP doesn\(aqt fail, it succeeds or crashes). This means that if you\(aqre trying to index something that cannot be indexed, you\(aqre on your own. Lua will call its \fBpanic()\fP function. See sec\-lua\-panic\&. .sp There are also free functions that can be used for indexing the table, see \fI\%Related functions\fP\&. .sp The constructor that takes a \fBfrom_stack\fP object is used when you want to initialize the object with a value from the lua stack. The \fBfrom_stack\fP type has the following constructor: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from_stack(lua_State* L, int index); .ft P .fi .UNINDENT .UNINDENT .sp The index is an ordinary lua stack index, negative values are indexed from the top of the stack. You use it like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object o(from_stack(L, \-1)); .ft P .fi .UNINDENT .UNINDENT .sp This will create the object \fBo\fP and copy the value from the top of the lua stack. .sp The \fBinterpreter()\fP 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 \fBpush()\fP\&. .sp The operator== will call lua_compare() on the operands and return its result. .sp The \fBis_valid()\fP 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. .sp The \fBoperator safe_bool_type()\fP is equivalent to \fBis_valid()\fP\&. This means that these snippets are equivalent: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object o; // ... if (o) { // ... } \&... object o; // ... if (o.is_valid()) { // ... } .ft P .fi .UNINDENT .UNINDENT .sp The application operator will call the value as if it was a function. You can give it any number of parameters (currently the \fBdefault_policy\fP 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 \fBluabind::error\fP 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C my_function_object( 2 , 8 , new my_complex_structure(6) ) [ adopt(_3) ]; .ft P .fi .UNINDENT .UNINDENT .sp This tells luabind to make Lua adopt the ownership and responsibility for the pointer passed in to the lua\-function. .sp It\(aqs 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. .sp Here\(aqs an example of how a function can use a table: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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(table[5]) << "\en"; } } .ft P .fi .UNINDENT .UNINDENT .sp If you take a \fBluabind::object\fP as a parameter to a function, any Lua value will match that parameter. That\(aqs why we have to make sure it\(aqs a table before we index into it. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C std::ostream& operator<<(std::ostream&, object const&); .ft P .fi .UNINDENT .UNINDENT .sp There\(aqs a stream operator that makes it possible to print objects or use \fBboost::lexical_cast\fP to convert it to a string. This will use lua\(aqs string conversion function. So if you convert a C++ object with a \fBtostring\fP operator, the stream operator for that type will be used. .SS Iterators .sp 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 \fBluabind::iterator\fP\&. The other iterator is called \fBluabind::raw_iterator\fP and will bypass the metamethod and give the true contents of the table. They have identical interfaces, which implements the \fI\%ForwardIterator\fP concept. Apart from the members of standard iterators, they have the following members and constructors: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class iterator { iterator(); iterator(object const&); object key() const; \fIstandard iterator members\fP }; .ft P .fi .UNINDENT .UNINDENT .sp The constructor that takes a \fBluabind::object\fP 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. .sp The default constructor will initialize the iterator to the one\-past\-end iterator. This is used to test for the end of the sequence. .sp The value type of the iterator is an implementation defined proxy type which supports the same operations as \fBluabind::object\fP\&. 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. .sp The \fBkey()\fP member returns the key used by the iterator when indexing the associated Lua table. .sp An example using iterators: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for (iterator i(globals(L)["a"]), end; i != end; ++i) { *i = 1; } .ft P .fi .UNINDENT .UNINDENT .sp The iterator named \fBend\fP 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 \fBa\fP and set all its values to 1. .SS Related functions .sp There are a couple of functions related to objects and tables. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int type(object const&); .ft P .fi .UNINDENT .UNINDENT .sp This function will return the lua type index of the given object. i.e. \fBLUA_TNIL\fP, \fBLUA_TNUMBER\fP etc. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template void settable(object const& o, K const& key, T const& value); template object gettable(object const& o, K const& key); template void rawset(object const& o, K const& key, T const& value); template object rawget(object const& o, K const& key); .ft P .fi .UNINDENT .UNINDENT .sp These functions are used for indexing into tables. \fBsettable\fP and \fBgettable\fP translates into calls to \fBlua_settable\fP and \fBlua_gettable\fP respectively. Which means that you could just as well use the index operator of the object. .sp \fBrawset\fP and \fBrawget\fP will translate into calls to \fBlua_rawset\fP and \fBlua_rawget\fP respectively. So they will bypass any metamethod and give you the true value of the table entry. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template T object_cast(object const&); template T object_cast(object const&, Policies); template boost::optional object_cast_nothrow(object const&); template boost::optional object_cast_nothrow(object const&, Policies); .ft P .fi .UNINDENT .UNINDENT .sp The \fBobject_cast\fP 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 \fBcast_failed\fP 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 \fBboost::optional\fP object, to indicate that the cast could not be performed. .sp 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\(aqs why it\(aqs left out of the documentation. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object globals(lua_State*); object registry(lua_State*); .ft P .fi .UNINDENT .UNINDENT .sp These functions return the global environment table and the registry table respectively. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object newtable(lua_State*); .ft P .fi .UNINDENT .UNINDENT .sp This function creates a new table and returns it as an object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object getmetatable(object const& obj); void setmetatable(object const& obj, object const& metatable); .ft P .fi .UNINDENT .UNINDENT .sp These functions get and set the metatable of a Lua object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C lua_CFunction tocfunction(object const& value); template T* touserdata(object const& value) .ft P .fi .UNINDENT .UNINDENT .sp These extract values from the object at a lower level than \fBobject_cast()\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C object getupvalue(object const& function, int index); void setupvalue(object const& function, int index, object const& value); .ft P .fi .UNINDENT .UNINDENT .sp These get and set the upvalues of \fBfunction\fP\&. .SS Assigning nil .sp To set a table entry to \fBnil\fP, you can use \fBluabind::nil\fP\&. It will avoid having to take the detour by first assigning \fBnil\fP to an object and then assign that to the table entry. It will simply result in a \fBlua_pushnil()\fP call, instead of copying an object. .sp Example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C using luabind; object table = newtable(L); table["foo"] = "bar"; // now, clear the "foo"\-field table["foo"] = nil; .ft P .fi .UNINDENT .UNINDENT .SH DEFINING CLASSES IN LUA .sp In addition to binding C++ functions and classes with Lua, luabind also provide an OO\-system in Lua. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class \(aqlua_testclass\(aq function lua_testclass:__init(name) self.name = name end function lua_testclass:print() print(self.name) end a = lua_testclass(\(aqexample\(aq) a:print() .ft P .fi .UNINDENT .UNINDENT .sp Inheritance can be used between lua\-classes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class \(aqderived\(aq (lua_testclass) function derived:__init() lua_testclass.__init(self, \(aqderived name\(aq) end function derived:print() print(\(aqDerived:print() \-> \(aq) lua_testclass.print(self) end .ft P .fi .UNINDENT .UNINDENT .sp The base class is initialized explicitly by calling its \fB__init()\fP function. .sp 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 (\fBself\fP) as first argument. .SS Deriving in lua .sp 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class base { public: base(const char* s) { std::cout << s << "\en"; } virtual void f(int a) { std::cout << "f(" << a << ")\en"; } }; struct base_wrapper : base, luabind::wrap_base { base_wrapper(const char* s) : base(s) {} virtual void f(int a) { call("f", a); } static void default_f(base* ptr, int a) { return ptr\->base::f(a); } }; // ... module(L) [ class_("base") .def(constructor()) .def("f", &base::f, &base_wrapper::default_f) ]; .ft P .fi .UNINDENT .UNINDENT .sp \fBIMPORTANT:\fP .INDENT 0.0 .INDENT 3.5 Since MSVC6.5 doesn\(aqt support explicit template parameters to member functions, instead of using the member function \fBcall()\fP you call a free function \fBcall_member()\fP and pass the this\-pointer as first parameter. .UNINDENT .UNINDENT .sp 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 \fBclass_\fP (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. .sp \fBIMPORTANT:\fP .INDENT 0.0 .INDENT 3.5 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\(aqt matter, but the parameters as seen from lua must match. It would not have worked if the static function took a \fBbase_wrapper*\fP as its first argument, since the virtual function takes a \fBbase*\fP as its first argument (its this pointer). There\(aqs currently no check in luabind to make sure the signatures match. .UNINDENT .UNINDENT .sp If we didn\(aqt 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\(aqs why we need one function that calls the base class\(aq real function (used if the lua class doesn\(aqt 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\(aqt intend to derive from a C++ class, or if it doesn\(aqt have any virtual member functions, you can register it without a class wrapper. .sp You don\(aqt need to have a class wrapper in order to derive from a class, but if it has virtual functions you may have silent errors. .sp The wrappers must derive from \fBluabind::wrap_base\fP, 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: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C template Ret call(char const* name, ...) .ft P .fi .UNINDENT .UNINDENT .sp Its used in a similar way as \fBcall_function\fP, with the exception that it doesn\(aqt take a \fBlua_State\fP pointer, and the name is a member function in the Lua class. .sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 The current implementation of \fBcall_member\fP 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 \fBcall_member\fP\&. This is rarely the case though. .UNINDENT .UNINDENT .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class "D" (B) function D:__init() B.__init(self) end function D:virtual_function() ... end .ft P .fi .UNINDENT .UNINDENT .sp you may be able to get around with .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C b = B() function b:virtual_function() ... end .ft P .fi .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS Object identity .sp When a pointer or reference to a registered class with a wrapper is passed to Lua, luabind will query for it\(aqs dynamic type. If the dynamic type inherits from \fBwrap_base\fP, object identity is preserved. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { .. }; struct A_wrap : A, wrap_base { .. }; A* f(A* ptr) { return ptr; } module(L) [ class_("A"), def("f", &f) ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C > class \(aqB\(aq (A) > x = B() > assert(x == f(x)) \-\- object identity is preserved when object is \-\- passed through C++ .ft P .fi .UNINDENT .UNINDENT .sp This functionality relies on RTTI being enabled (that \fBLUABIND_NO_RTTI\fP is not defined). .SS Overloading operators .sp 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: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 \fB__add\fP .IP \(bu 2 \fB__sub\fP .IP \(bu 2 \fB__mul\fP .IP \(bu 2 \fB__div\fP .IP \(bu 2 \fB__pow\fP .IP \(bu 2 \fB__lt\fP .IP \(bu 2 \fB__le\fP .IP \(bu 2 \fB__eq\fP .IP \(bu 2 \fB__call\fP .IP \(bu 2 \fB__unm\fP .IP \(bu 2 \fB__tostring\fP .IP \(bu 2 \fB__len\fP .UNINDENT .UNINDENT .UNINDENT .sp \fB__tostring\fP isn\(aqt really an operator, but it\(aqs the metamethod that is called by the standard library\(aqs \fBtostring()\fP function. There\(aqs 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\(aqt distinguish the two cases where you get the other operand as left hand value or right hand value. Consider the following examples: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class \(aqmy_class\(aq function my_class:__init(v) self.val = v end function my_class:__sub(v) return my_class(self.val \- v.val) end function my_class:__tostring() return self.val end .ft P .fi .UNINDENT .UNINDENT .sp 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C function my_class:__sub(v) if (type(self) == \(aqnumber\(aq) then return my_class(self \- v.val) elseif (type(v) == \(aqnumber\(aq) then return my_class(self.val \- v) else \-\- assume both operands are instances of my_class return my_class(self.val \- v.val) end end .ft P .fi .UNINDENT .UNINDENT .sp The reason why \fB__sub\fP is used as an example is because subtraction is not commutative (the order of the operands matters). That\(aqs why luabind cannot change order of the operands to make the self reference always refer to the actual class instance. .sp 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\(aq operator. If none of the C++ overloads matches, the Lua class operator will be called. .SS Finalizers .sp If an object needs to perform actions when it\(aqs collected we provide a \fB__finalize\fP function that can be overridden in lua\-classes. The \fB__finalize\fP functions will be called on all classes in the inheritance chain, starting with the most derived type. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&... function lua_testclass:__finalize() \-\- called when the an object is collected end .ft P .fi .UNINDENT .UNINDENT .SS Slicing .sp If your lua C++ classes don\(aqt have wrappers (see \fI\%Deriving in lua\fP) 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ | 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++. .ft P .fi .UNINDENT .UNINDENT .sp The problem can be illustrated by this example: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A {}; A* filter_a(A* a) { return a; } void adopt_a(A* a) { delete a; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C using namespace luabind; module(L) [ class_("A"), def("filter_a", &filter_a), def("adopt_a", &adopt_a, adopt(_1)) ] .ft P .fi .UNINDENT .UNINDENT .sp In lua: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C a = A() b = filter_a(a) adopt_a(b) .ft P .fi .UNINDENT .UNINDENT .sp In this example, lua cannot know that \fBb\fP actually is the same object as \fBa\fP, and it will therefore consider the object to be owned by the C++ side. When the \fBb\fP pointer then is adopted, a runtime error will be raised because an object not owned by lua is being adopted to C++. .sp If you have a wrapper for your class, none of this will happen, see \fI\%Object identity\fP\&. .SH EXCEPTIONS .sp 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 \fBlua_error()\fP will be invoked. If the exception is a \fBstd::exception\fP or a \fBconst char*\fP the string that is pushed on the Lua stack, as error message, will be the string returned by \fBstd::exception::what()\fP or the string itself respectively. If the exception is unknown, a generic string saying that the function threw an exception will be pushed. .sp If you have an exception type that isn\(aqt derived from \fBstd::exception\fP, or you wish to change the error message from the default result of \fBwhat()\fP, it is possible to register custom exception handlers: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct my_exception {}; void translate_my_exception(lua_State* L, my_exception const&) { lua_pushstring(L, "my_exception"); } … luabind::register_exception_handler(&translate_my_exception); .ft P .fi .UNINDENT .UNINDENT .sp \fBtranslate_my_exception()\fP will be called by luabind whenever a \fBmy_exception\fP is caught. \fBlua_error()\fP will be called after the handler function returns, so it is expected that the function will push an error string on the stack. .sp Any function that invokes Lua code may throw \fBluabind::error\fP\&. 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\(aqt 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. .sp Error\(aqs synopsis is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class error : public std::exception { public: error(lua_State*); lua_State* state() const throw(); virtual const char* what() const throw(); }; .ft P .fi .UNINDENT .UNINDENT .sp 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. .sp An example of where the Lua state pointer may point to an invalid state follows: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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() { try { 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 /* ... */ } } .ft P .fi .UNINDENT .UNINDENT .sp There\(aqs another exception that luabind may throw: \fBluabind::cast_failed\fP, this exception is thrown from \fBcall_function<>\fP or \fBcall_member<>\fP\&. It means that the return value from the Lua function couldn\(aqt be converted to a C++ value. It is also thrown from \fBobject_cast<>\fP if the cast cannot be made. .sp The synopsis for \fBluabind::cast_failed\fP is: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C class cast_failed : public std::exception { public: cast_failed(lua_State*); lua_State* state() const throw(); LUABIND_TYPE_INFO info() const throw(); virtual const char* what() const throw(); }; .ft P .fi .UNINDENT .UNINDENT .sp 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. .sp The info member function returns the user defined \fBLUABIND_TYPE_INFO\fP, which defaults to a \fBconst std::type_info*\fP\&. This type info describes the type that we tried to cast a Lua value to. .sp If you have defined \fBLUABIND_NO_EXCEPTIONS\fP 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 \fBLUABIND_NO_EXCEPTIONS\fP are defined. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C luabind::set_error_callback(void(*)(lua_State*)) .ft P .fi .UNINDENT .UNINDENT .sp 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 \fBstd::terminate()\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO)) .ft P .fi .UNINDENT .UNINDENT .sp The function you set is called instead of throwing \fBcast_failed\fP\&. This function is not expected to return, if it does luabind will call \fBstd::terminate()\fP\&. .SH POLICIES .sp 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 \fBresult\fP and \fB_N\fP (where \fBN >= 1\fP). When dealing with member functions \fB_1\fP refers to the \fBthis\fP pointer. .SS Policies currently implemented .INDENT 0.0 .IP \(bu 2 \fI\%adopt\fP .IP \(bu 2 \fI\%dependency\fP .IP \(bu 2 \fI\%out_value\fP .IP \(bu 2 \fI\%pure_out_value\fP .IP \(bu 2 \fI\%return_reference_to\fP .IP \(bu 2 \fI\%copy\fP .IP \(bu 2 \fI\%discard_result\fP .IP \(bu 2 \fI\%return_stl_iterator\fP .IP \(bu 2 \fI\%raw\fP .IP \(bu 2 \fI\%yield\fP .UNINDENT .SS adopt .SS Motivation .sp Used to transfer ownership across language boundaries. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C adopt(index) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The index which should transfer ownership, \fB_N\fP or \fBresult\fP T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C X* create() { return new X; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("create", &create, \fBadopt(result)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .SS dependency .SS Motivation .sp The dependency policy is used to create life\-time dependencies between values. This is needed for example when returning internal references to some class. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C dependency(nurse_index, patient_index) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBnurse_index\fP T} T{ The index which will keep the patient alive. T} _ T{ \fBpatient_index\fP T} T{ The index which will be kept alive. T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct X { B member; B& get() { return member; } }; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("X") .def("get", &X::get, \fBdependency(result, _1)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .SS out_value .SS Motivation .sp This policy makes it possible to wrap functions that take non\-const references or pointer to non\-const as it\(aqs parameters with the intention to write return values to them. Since it\(aqs impossible to pass references to primitive types in lua, this policy will add another return value with the value after the call. If the function already has one return value, one instance of this policy will add another return value (read about multiple return values in the lua manual). .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C out_value(index, policies = none) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The index of the parameter to be used as an out parameter. T} _ T{ \fBpolicies\fP T} T{ The policies used internally to convert the out parameter to/from Lua. \fB_1\fP means \fBto\fP C++, \fB_2\fP means \fBfrom\fP C++. T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void f1(float& val) { val = val + 10.f; } void f2(float* val) { *val = *val + 10.f; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("f", &f, \fBout_value(_1)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Lua 5.0 Copyright (C) 1994\-2003 Tecgraf, PUC\-Rio > print(f1(10)) 20 > print(f2(10)) 20 .ft P .fi .UNINDENT .UNINDENT .SS pure_out_value .SS Motivation .sp This works exactly like \fBout_value\fP, except that it will pass a default constructed object instead of converting an argument from Lua. This means that the parameter will be removed from the lua signature. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C pure_out_value(index, policies = none) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The index of the parameter to be used as an out parameter. T} _ T{ \fBpolicies\fP T} T{ The policies used internally to convert the out parameter to Lua. \fB_1\fP is used as the internal index. T} _ .TE .SS Example .sp Note that no values are passed to the calls to \fBf1\fP and \fBf2\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void f1(float& val) { val = 10.f; } void f2(float\e* val) { \e*val = 10.f; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("f", &f, \fBpure_out_value(_1)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Lua 5.0 Copyright (C) 1994\-2003 Tecgraf, PUC\-Rio > print(f1()) 10 > print(f2()) 10 .ft P .fi .UNINDENT .UNINDENT .SS return_reference_to .SS Motivation .sp It is very common to return references to arguments or the this\-pointer to allow for chaining in C++. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { float val; A& set(float v) { val = v; return *this; } }; .ft P .fi .UNINDENT .UNINDENT .sp When luabind generates code for this, it will create a new object for the return\-value, pointing to the self\-object. This isn\(aqt a problem, but could be a bit inefficient. When using the return_reference_to\-policy we have the ability to tell luabind that the return\-value is already on the lua stack. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C return_reference_to(index) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The argument index to return a reference to, any argument but not \fBresult\fP\&. T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct A { float val; A& set(float v) { val = v; return *this; } }; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A") .def(constructor<>()) .def("set", &A::set, \fBreturn_reference_to(_1)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .sp \fBWARNING:\fP .INDENT 0.0 .INDENT 3.5 This policy ignores all type information and should be used only it situations where the parameter type is a perfect match to the return\-type (such as in the example). .UNINDENT .UNINDENT .SS copy .SS Motivation .sp This will make a copy of the parameter. This is the default behavior when passing parameters by\-value. Note that this can only be used when passing from C++ to Lua. This policy requires that the parameter type has an accessible copy constructor. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C copy(index) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The index to copy. \fBresult\fP when used while wrapping C++ functions. \fB_N\fP when passing arguments to Lua. T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C X* get() { static X instance; return &instance; } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("create", &create, \fBcopy(result)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .SS discard_result .SS Motivation .sp This is a very simple policy which makes it possible to throw away the value returned by a C++ function, instead of converting it to Lua. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C discard_result .ft P .fi .UNINDENT .UNINDENT .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct X { X& set(T n) { ... return *this; } }; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("X") .def("set", &simple::set, \fBdiscard_result\fP) ]; .ft P .fi .UNINDENT .UNINDENT .SS return_stl_iterator .SS Motivation .sp This policy converts an STL container to a generator function that can be used in lua to iterate over the container. It works on any container that defines \fBbegin()\fP and \fBend()\fP member functions (they have to return iterators). .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C return_stl_iterator .ft P .fi .UNINDENT .UNINDENT .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C struct X { std::vector names; }; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_("A") .def_readwrite("names", &X::names, \fBreturn_stl_iterator\fP) ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C > a = A() > for name in a.names do > print(name) > end .ft P .fi .UNINDENT .UNINDENT .SS raw .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 \fBraw()\fP has been deprecated. \fBlua_State*\fP parameters are automatically handled by luabind. .UNINDENT .UNINDENT .SS Motivation .sp This converter policy will pass through the \fBlua_State*\fP unmodified. This can be useful for example when binding functions that need to return a \fBluabind::object\fP\&. The parameter will be removed from the function signature, decreasing the function arity by one. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C raw(index) .ft P .fi .UNINDENT .UNINDENT .SS Parameters .TS center; |l|l|. _ T{ Parameter T} T{ Purpose T} _ T{ \fBindex\fP T} T{ The index of the lua_State* parameter. T} _ .TE .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void greet(lua_State* L) { lua_pushstring(L, "hello"); } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("greet", &greet, \fBraw(_1)\fP) ]; .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C > print(greet()) hello .ft P .fi .UNINDENT .UNINDENT .SS yield .SS Motivation .sp Makes a C++ function yield when returning. .SS Defined in .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C #include .ft P .fi .UNINDENT .UNINDENT .SS Synopsis .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C yield .ft P .fi .UNINDENT .UNINDENT .SS Example .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void do_thing_that_takes_time() { // ... } .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C module(L) [ def("do_thing_that_takes_time", &do_thing_that_takes_time, \fByield\fP) ]; .ft P .fi .UNINDENT .UNINDENT .SH SPLITTING UP THE REGISTRATION .sp It is possible to split up a module registration into several translation units without making each registration dependent on the module it\(aqs being registered in. .sp \fBa.cpp\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C luabind::scope register_a() { return class_("a") .def("f", &a::f) ; } .ft P .fi .UNINDENT .UNINDENT .sp \fBb.cpp\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C luabind::scope register_b() { return class_("b") .def("g", &b::g) ; } .ft P .fi .UNINDENT .UNINDENT .sp \fBmodule_ab.cpp\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C luabind::scope register_a(); luabind::scope register_b(); void register_module(lua_State* L) { module("b", L) [ register_a(), register_b() ]; } .ft P .fi .UNINDENT .UNINDENT .SH ERROR HANDLING .SS pcall errorfunc .sp As mentioned in the \fI\%Lua documentation\fP, it is possible to pass an error handler function to \fBlua_pcall()\fP\&. Luabind makes use of \fBlua_pcall()\fP internally when calling member functions and free functions. It is possible to set the error handler function that Luabind will use globally: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C typedef int(*pcall_callback_fun)(lua_State*); void set_pcall_callback(pcall_callback_fun fn); .ft P .fi .UNINDENT .UNINDENT .sp This is primarily useful for adding more information to the error message returned by a failed protected call. For more information on how to use the pcall_callback function, see \fBerrfunc\fP under the \fI\%pcall section of the lua manual\fP\&. .sp For more information on how to retrieve debugging information from lua, see \fI\%the debug section of the lua manual\fP\&. .sp The message returned by the \fBpcall_callback\fP is accessible as the top lua value on the stack. For example, if you would like to access it as a luabind object, you could do like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C catch(error& e) { object error_msg(from_stack(e.state(), \-1)); std::cout << error_msg << std::endl; } .ft P .fi .UNINDENT .UNINDENT .SS file and line numbers .sp If you want to add file name and line number to the error messages generated by luabind you can define your own \fI\%pcall errorfunc\fP\&. You may want to modify this callback to better suit your needs, but the basic functionality could be implemented like this: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C int add_file_and_line(lua_State* L) { lua_Debug d; lua_getstack(L, 1, &d); lua_getinfo(L, "Sln", &d); std::string err = lua_tostring(L, \-1); lua_pop(L, 1); std::stringstream msg; msg << d.short_src << ":" << d.currentline; if (d.name != 0) { msg << "(" << d.namewhat << " " << d.name << ")"; } msg << " " << err; lua_pushstring(L, msg.str().c_str()); return 1; } .ft P .fi .UNINDENT .UNINDENT .sp For more information about what kind of information you can add to the error message, see \fI\%the debug section of the lua manual\fP\&. .sp Note that the callback set by \fBset_pcall_callback()\fP will only be used when luabind executes lua code. Anytime when you call \fBlua_pcall\fP yourself, you have to supply your function if you want error messages translated. .SS lua panic .sp When lua encounters a fatal error caused by a bug from the C/C++ side, it will call its internal panic function. This can happen, for example, when you call \fBlua_gettable\fP on a value that isn\(aqt a table. If you do the same thing from within lua, it will of course just fail with an error message. .sp The default panic function will \fBexit()\fP the application. If you want to handle this case without terminating your application, you can define your own panic function using \fBlua_atpanic\fP\&. The best way to continue from the panic function is to make sure lua is compiled as C++ and throw an exception from the panic function. Throwing an exception instead of using \fBsetjmp\fP and \fBlongjmp\fP will make sure the stack is correctly unwound. .sp When the panic function is called, the lua state is invalid, and the only allowed operation on it is to close it. .sp For more information, see the \fI\%lua manual section 3.19\fP\&. .SS structured exceptions (MSVC) .sp Since lua is generally built as a C library, any callbacks called from lua cannot under any circumstance throw an exception. Because of that, luabind has to catch all exceptions and translate them into proper lua errors (by calling \fBlua_error()\fP). This means we have a \fBcatch(...) {}\fP in there. .sp In Visual Studio, \fBcatch (...)\fP will not only catch C++ exceptions, it will also catch structured exceptions, such as segmentation fault. This means that if your function, that gets called from luabind, makes an invalid memory addressing, you won\(aqt notice it. All that will happen is that lua will return an error message saying "unknown exception". .sp To remedy this, you can create your own \fIexception translator\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } #ifdef _MSC_VER ::_set_se_translator(straight_to_debugger); #endif .ft P .fi .UNINDENT .UNINDENT .sp This will make structured exceptions, like segmentation fault, to actually get caught by the debugger. .SS Error messages .sp These are the error messages that can be generated by luabind, with a more in\-depth explanation. .INDENT 0.0 .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C the attribute \(aq\fIclass\-name.attribute\-name\fP\(aq is read only .ft P .fi .UNINDENT .UNINDENT .sp There is no data member named \fIattribute\-name\fP in the class \fIclass\-name\fP, or there\(aqs no setter\-function registered on that property name. See the sec\-properties section. .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C the attribute \(aq\fIclass\-name.attribute\-name\fP\(aq is of type: (\fIclass\-name\fP) and does not match (\fIclass_name\fP) .ft P .fi .UNINDENT .UNINDENT .sp This error is generated if you try to assign an attribute with a value of a type that cannot be converted to the attributes type. .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C \fIclass\-name()\fP threw an exception, \fIclass\-name:function\-name()\fP threw an exception .ft P .fi .UNINDENT .UNINDENT .sp The class\(aq constructor or member function threw an unknown exception. Known exceptions are const char*, std::exception. See the part\-exceptions section. .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C no overload of \(aq\fIclass\-name:function\-name\fP\(aq matched the arguments (\fIparameter\-types\fP) no match for function call \(aq\fIfunction\-name\fP\(aq with the parameters (\fIparameter\-types\fP) no constructor of \fIclass\-name\fP matched the arguments (\fIparameter\-types\fP) no operator \fIoperator\-name\fP matched the arguments (\fIparameter\-types\fP) .ft P .fi .UNINDENT .UNINDENT .sp No function/operator with the given name takes the parameters you gave it. You have either misspelled the function name, or given it incorrect parameters. This error is followed by a list of possible candidate functions to help you figure out what parameter has the wrong type. If the candidate list is empty there\(aqs no function at all with that name. See the signature matching section. .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C call of overloaded \(aq\fIclass\-name:function\-name*(*parameter\-types\fP)\(aq is ambiguous ambiguous match for function call \(aq\fIfunction\-name\fP\(aq with the parameters (\fIparameter\-types\fP) call of overloaded constructor \(aq\fIclass\-name*(*parameter\-types\fP)\(aq is ambiguous call of overloaded operator \fIoperator\-name\fP (\fIparameter\-types\fP) is ambiguous .ft P .fi .UNINDENT .UNINDENT .sp This means that the function/operator you are trying to call has at least one other overload that matches the arguments just as good as the first overload. .IP \(bu 2 .INDENT 2.0 .INDENT 3.5 .sp .nf .ft C cannot derive from C++ class \(aq\fIclass\-name\fP\(aq. It does not have a wrapped type. .ft P .fi .UNINDENT .UNINDENT .UNINDENT .SH BUILD OPTIONS .sp There are a number of configuration options (preprocessor \fB#define\fPs available when building luabind. It is very important that your project has the exact same configuration options as the ones given when the library was build! The exceptions are the \fBLUABIND_MAX_ARITY\fP and \fBLUABIND_MAX_BASES\fP which are template\-based options and only matters when you use the library (which means they can differ from the settings of the library). To achieve this you should use the CMake equivalent of these options. Then, when building with CMake the \fBbuild_information.hpp\fP header is created and automatically included by \fBconfig.hpp\fP, thus keeping the options in sync automatically. .INDENT 0.0 .TP .B \fBLUABIND_MAX_ARITY\fP Controls the maximum arity of functions that are registered with luabind. You can\(aqt register functions that takes more parameters than the number this macro is set to. It defaults to 5, so, if your functions have greater arity you have to redefine it. A high limit will increase compilation time. .TP .B \fBLUABIND_MAX_BASES\fP Controls the maximum number of classes one class can derive from in luabind (the number of classes specified within \fBbases<>\fP). \fBLUABIND_MAX_BASES\fP defaults to 4. A high limit will increase compilation time. .TP .B \fBLUABIND_NO_ERROR_CHECKING\fP If this macro is defined, all the Lua code is expected only to make legal calls. If illegal function calls are made (e.g. giving parameters that doesn\(aqt match the function signature) they will not be detected by luabind and the application will probably crash. Error checking could be disabled when shipping a release build (given that no end\-user has access to write custom Lua code). Note that function parameter matching will be done if a function is overloaded, since otherwise it\(aqs impossible to know which one was called. Functions will still be able to throw exceptions when error checking is disabled. .sp If a function throws an exception it will be caught by luabind and propagated with \fBlua_error()\fP\&. .TP .B \fBLUABIND_NO_EXCEPTIONS\fP This define will disable all usage of try, catch and throw in luabind. This will in many cases disable run\-time errors, when performing invalid casts or calling Lua functions that fails or returns values that cannot be converted by the given policy. luabind requires that no function called directly or indirectly by luabind throws an exception (throwing exceptions through Lua has undefined behavior). .sp Where exceptions are the only way to get an error report from luabind, they will be replaced with calls to the callback functions set with \fBset_error_callback()\fP and \fBset_cast_failed_callback()\fP\&. .TP .B \fBLUA_API\fP If you want to link dynamically against Lua, you can set this define to the import\-keyword on your compiler and platform. On Windows in Visual Studio this should be \fB__declspec(dllimport)\fP if you want to link against Lua as a dll. .TP .B \fBLUABIND_DYNAMIC_LINK\fP Must be defined if you intend to link against the luabind shared library (.so or DLL) / build it as such. Note that in future versions of luabind, this option may be dependent on \fBBUILD_SHARED_LIBS\fP in CMake, so you should always set both CMake options to the same value. .sp If enabling this, you should link Lua dynamically to both Luabind and your application. If you encounter double\-free errors or other memory corruption, this might be the problem. .TP .B \fBLUABIND_CPLUSPLUS_LUA\fP Without this, all included Lua headers will be wrapped in \fBextern "C"\fP\&. Define this if you compiled Lua as C++. .TP .B \fBNDEBUG\fP This define will disable all asserts and should be defined in a release build. .TP .B \fBLUABIND_USE_NOEXCEPT\fP If you use Boost <= 1.46 but your compiler is C++11 compliant and marks destructors as noexcept by default, you need to define LUABIND_USE_NOEXCEPT. Failing to do so will cause std::terminate() being called if a destructor throws (e.g. the destructor of the proxy returned by \fBcall_function\fP or \fBobject::operator()\fP). .TP .B \fBLUABIND_LIBRARY_VERSION\fP Specify the version of luabind being built, in x.y.z form. .UNINDENT .SS CMake options .sp The following options can be given to CMake when building luabind. You can either specify them directly on the commandline using \fB\-Doption=value\fP or let CMake ask you for each of them by invoking it with the \fB\-i\fP flag. On Windows, you will usually prefer \fBcmake\-gui\fP\&. .sp All options are booleans, unless specified otherwise. .INDENT 0.0 .TP .B \fBLUABIND_ENABLE_WARNINGS\fP Enable compiler warnings during the build of luabind and the tests. .TP .B \fBLUABIND_USE_CXX11\fP This controls whether the \fB\-std=c++11\fP flag is passed to compilers that support it. And whether support for C++11 scoped enums can be enabled. .TP .B \fBBUILD_TESTING\fP Whether to generate build files for the unit tests (they must be run manually in any case). .TP .B \fBLUABIND_BUILD_HEADER_TESTS\fP Enable this for (many) additional compilation tests: Each of Luabind’s public headers will be included in a generated .cpp file which otherwise only contains an empty main function, meaning that one dummy binary per header file is generated. .sp This can only be enabled if \fBBUILD_TESTING\fP is enabled. .TP .B \fBLUABIND_APPEND_VERSION_SUFFIX\fP With this option set (the default), built binaries and object archives will be named e.g. \fBluabind09.dll\fP instead of just \fBluabind.dll\fP\&. .TP .B \fBLUABIND_LUA_VERSION\fP A string variable with defaults to \fB""\fP (the empty string). It can be set to \fB"51"\fP or \fB"52"\fP to use the respective Lua versions. If left empty, Lua52 will be tried first before falling back to Lua51. .TP .B \fBCMAKE_BUILD_TYPE\fP String option. See the corresponding entry in the CMake manual. .UNINDENT .SH IMPLEMENTATION NOTES .sp The classes and objects are implemented as user data in Lua. To make sure that the user data really is the internal structure it is supposed to be, we tag their metatables. Previously a boolean at a string key was used, making it relatively easy for the malevolent user to fool Luabind and crash the application. However, this has been replaced with a light userdata key that should be quite impossible to imitate. .sp In the Lua registry, luabind kept an entry called \fB"__luabind_classes"\fP\&. This string key is now also replaced with a light userdata one. .sp In the global table, a variable called \fBsuper\fP is used every time a constructor in a lua\-class is called. This is to make it easy for that constructor to call its base class\(aq constructor. So, if you have a global variable named super it may be overwritten. This is probably not the best solution, and this restriction may be removed in the future. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 Deprecated .sp \fBsuper()\fP has been deprecated since version 0.8 in favor of directly invoking the base class\(aq \fB__init()\fP function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C function Derived:__init() Base.__init(self) end .ft P .fi .UNINDENT .UNINDENT .UNINDENT .UNINDENT .SS The detail namespace and undocumented features .sp Inside the luabind namespace, there’s another namespace called \fBdetail\fP\&. Everything cotained therein should not be used by user code and is subject to change or vanish even between patch versions. There also exist no explicit tests or documentation for this namespace’s contents. .sp Classes and functions which reside directly in the \fBluabind\fP namespace but are not documented should also rather not be used. However, if you have to depend on undocumented features, these are still better than the \fBdetail\fP ones. .SH FAQ .INDENT 0.0 .TP .B What\(aqs up with __cdecl and __stdcall? If you\(aqre having problem with functions that cannot be converted from \fBvoid (__stdcall *)(int,int)\fP to \fBvoid (__cdecl*)(int,int)\fP\&. You can change the project settings to make the compiler generate functions with __cdecl calling conventions. This is a problem in developer studio. .TP .B What\(aqs wrong with functions taking variable number of arguments? You cannot register a function with ellipses in its signature. Since ellipses don\(aqt preserve type safety, those should be avoided anyway. .TP .B Internal structure overflow in VC If you, in visual studio, get fatal error C1204: compiler limit : internal structure overflow. You should try to split that compilation unit up in smaller ones. See part\-split\-registration and sec\-split\-cls\-registration\&. .TP .B What\(aqs wrong with precompiled headers in VC? Visual Studio doesn\(aqt like anonymous namespaces in its precompiled headers. If you encounter this problem you can disable precompiled headers for the compilation unit (cpp\-file) that uses luabind. .TP .B error C1076: compiler limit \- internal heap limit reached in VC In visual studio you will probably hit this error. To fix it you have to increase the internal heap with a command\-line option. We managed to compile the test suit with /Zm300, but you may need a larger heap then that. .TP .B error C1055: compiler limit : out of keys in VC It seems that this error occurs when too many assert() are used in a program, or more specifically, the __LINE__ macro. It seems to be fixed by changing /ZI (Program database for edit and continue) to /Zi (Program database). .TP .B How come my executable is huge? If you\(aqre compiling in debug mode, you will probably have a lot of debug\-info and symbols (luabind consists of a lot of functions). Also, if built in debug mode, no optimizations were applied, luabind relies on that the compiler is able to inline functions. If you built in release mode, try running strip on your executable to remove export\-symbols, this will trim down the size. .sp Our tests suggests that cygwin\(aqs gcc produces much bigger executables compared to gcc on other platforms and other compilers. .UNINDENT .INDENT 0.0 .TP .B Can I register class templates with luabind? Yes you can, but you can only register explicit instantiations of the class. Because there\(aqs no Lua counterpart to C++ templates. For example, you can register an explicit instantiation of std::vector<> like this: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C module(L) [ class_ >("vector") .def(constructor) .def("push_back", &std::vector::push_back) ]; .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .TP .B Do I have to register destructors for my classes? No, the destructor of a class is always called by luabind when an object is collected. Note that Lua has to own the object to collect it. If you pass it to C++ and gives up ownership (with adopt policy) it will no longer be owned by Lua, and not collected. .sp If you have a class hierarchy, you should make the destructor virtual if you want to be sure that the correct destructor is called (this apply to C++ in general). .UNINDENT .INDENT 0.0 .TP .B Fatal Error C1063 compiler limit : compiler stack overflow in VC VC6.5 chokes on warnings, if you are getting a lot of warnings from your code try suppressing them with a pragma directive, this should solve the problem. .TP .B Crashes when linking against luabind as a dll in Windows When you build luabind, Lua and you project, make sure you link against the runtime dynamically (as a dll). .TP .B I cannot register a function with a non\-const parameter This is because there is no way to get a reference to a Lua value. Have a look at policy\-out_value and policy\-pure_out_value policies. .UNINDENT .SH KNOWN ISSUES .INDENT 0.0 .IP \(bu 2 You cannot use strings with extra nulls in them as member names that refers to C++ members. .IP \(bu 2 If one class registers two functions with the same name and the same signature, there\(aqs currently no error. The last registered function will be the one that\(aqs used. .IP \(bu 2 In VC7, classes can not be called test. .IP \(bu 2 If you register a function and later rename it, error messages will use the original function name. .IP \(bu 2 luabind does not support class hierarchies with virtual inheritance. Casts are done with static pointer offsets. .UNINDENT .SH ACKNOWLEDGMENTS .sp Written by Daniel Wallin and Arvid Norberg. © Copyright 2003. All rights reserved. .sp Evan Wies has contributed with thorough testing, countless bug reports and feature ideas. .sp Many features and fixes of this fork come from \fI\%Ryan Pavlik\(aqs (rpavlik) fork\fP and from \fI\%Peter Colberg (fhoefling\(aqs fork)\fP\&. .sp Christian Neumüller (Oberon00) is the maintainer of \fI\%this fork\fP\&. .sp A rather complete list of contributors can be found at \fI\%http://github.com/Oberon00/luabind/contributors\fP\&. .sp This library was highly inspired by Dave Abrahams\(aq \fI\%Boost.Python\fP library. .INDENT 0.0 .IP \(bu 2 search .UNINDENT .SH AUTHOR Daniel Wallin, Arvid Norberg .SH COPYRIGHT 2020 Rasterbar Software; 2013 Christian Neumüller .\" Generated by docutils manpage writer. .