LUABIND(3)
๐ LUABIND(3) โ Luabind ๐
okay bestie, welcome to the Luabind manual page. This is the Luabind Documentation, and we are about to get into it. No cap. ๐ฆ
๐ NAME ๐
luabind โ Luabind Documentation.
This is the documentation for Luabind 0.9.1d1 . (yes, there is a space before that period, and we respect it ๐
)
Luabind is a library that helps you create bindings between C++ and Lua. It has the ability to expose functions and classes, written in C++, to Lua. It will also supply the functionality to define classes in Lua and let them derive from other Lua classes or C++ classes. Lua classes can override virtual functions from their C++ base classes. It is written towards Lua 5.2 but should also work with 5.1.
The old official homepage can be found at <http://www.rasterbar.com/products/luabind.html>.
Contents:
๐ INTRODUCTION ๐
okay so real talk: Luabind is a library that helps you create bindings between C++ and Lua. It has the ability to expose functions and classes, written in C++, to Lua. It will also supply the functionality to define classes in Lua and let them derive from other Lua classes or C++ classes. Lua classes can override virtual functions from their C++ base classes. It is written towards Lua 5.2 but should also work with 5.1. ๐
It is implemented utilizing template meta programming. That means that you don't need an extra preprocess pass to compile your project (it is done by the compiler). It also means you don't (usually) have to know the exact signature of each function you register, since the library will generate code depending on the compile-time type of the function (which includes the signature). The main drawback of this approach is that the compilation time will increase for the file that does the registration, it is therefore recommended that you register everything in the same cpp-file.
Luabind is released under the terms of the MIT license <http://www.opensource.org/licenses/mit-license.php>.
We are very interested in hearing about projects that use luabind, please let us know about your project.
The main channel for help and feedback is the luabind mailing list <https://lists.sourceforge.net/lists/listinfo/luabind-user>. There's also an IRC channel #luabind on irc.freenode.net.
Additionally, this forkโs github issue tracker <https://github.com/Oberon00/luabind/issues> can also be used for bug reports, feature requests and questions.
โจ FEATURES โจ
Luabind supports, and I am obsessed:
- Overloaded free functions
- C++ classes in Lua
- Overloaded member functions
- Operators
- Properties
- Enums (also C++11 enum class if available)
- Lua functions in C++
- Lua classes in C++
- Lua classes (single inheritance)
- Derives from Lua or C++ classes
- Override virtual functions from C++ classes
- Implicit casts between registered types
- Best match signature matching
- Return value policies and parameter policies
๐ง PORTABILITY ๐ง
Luabind is currently tested regularly with
- Microsoft Visual C++ 11 (2012) x32 and x64
- gcc 4.8 x64 (with and without
-std=c++11) - Clang 3.2 x64 (with and without
-std=c++11)
It should work with any compiler conformant with C++03. However, probably only versions of the above threecompilers will work out of the box with the provided CMake build files. Please report any issues you have to the github issue tracker <https://github.com/Oberon00/luabind/issues>. ๐ธ
๐ BUILDING LUABIND ๐
๐ Prerequisites ๐
Apart from Lua 5.1 or (recommended) 5.2, Luabind depends on a number of Boost libraries. It also depends on CMake <http://www.cmake.org/> to build the library and run the tests.
๐ช Windows ๐ช
If CMake has problems finding Lua, LUA_DIR needs to be set to point to a directory containing the Lua include directory and built libraries.
The same applies to Boost and the BOOST_ROOT environment variable.
๐ง Linux and other *nix flavors ๐ง
If your system already has Lua installed, it is very likely that the build system will automatically find it and just work. If you have Lua installed in a non-standard location, you may need to set LUA_DIR to point to the installation prefix.
BOOST_ROOT can be set to a Boost installation directory. If left unset, the build system will try to use boost headers from the standard include path.
๐ฅ Building and testing ๐ฅ
Building the default variant of the library, which is a static release library, is simply done by invoking cmake in the luabind root directory and then running your native build tools on the generated files (e.g. make on Unix or nmake/msbuild ALL_BUILD.vcxproj for MSVC).
Note: To build your application against the shared library variant, LUABIND_DYNAMIC_LINK needs to be defined to properly import symbols.
To run the unit tests, invoke your build tool with the test target, e.g. make test on Unix or nmake test/msbuild RUN_TESTS.vcxproj for MSVC. This run the (previously built) unit tests in the current variant. A clean test run output should end with something like:
100% tests passed, 0 tests failed out of 51
Total Test time (real) = 1.23 sec
A failed run would end with something like:
98% tests passed, 1 tests failed out of 51
Total Test time (real) = 1.23 sec
The following tests FAILED:
1 - abstract_base (Failed)
๐ธ BASIC USAGE ๐ธ
To use luabind, you must include lua.h and luabind's main header file:
extern "C"
{
#include "lua.h"
}
#include <luabind/luabind.hpp>
This includes support for both registering classes and functions. If you just want to have support for functions or classes you can include luabind/function.hpp and luabind/class.hpp separately:
#include <luabind/function.hpp>
#include <luabind/class.hpp>
The first thing you need to do is to call luabind::open(lua_State*) which will register the functions to create classes from Lua, and initialize some state-global structures used by luabind. If you don't call this function you will hit asserts later in the library. There is no corresponding close function because once a class has been registered in Lua, there really isn't any good way to remove it. Partly because any remaining instances of that class relies on the class being there. Everything will be cleaned up when the state is closed though. ๐
Luabind's headers will never include lua.h directly, but through <luabind/lua_include.hpp>. If you for some reason need to include another Lua header, you can modify this file.
๐ Hello world ๐
#include <iostream>
#include <luabind/luabind.hpp>
void greet()
{
std::cout << "hello world!\n";
}
extern "C" int init(lua_State* L)
{
using namespace luabind;
open(L);
module(L)
[
def("greet", &greet)
];
return 0;
}
Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> loadlib('hello_world.dll', 'init')()
> greet()
Hello world!
>
๐ SCOPES ๐
Everything that gets registered in Lua is registered in a given Lua table, in a namespace (Lua table at given name), or in the global scope (called module). All registrations must be surrounded by its scope. To define a module, the luabind::module class is used. It is used like this:
module(L)
[
// declarations
];
This will register all declared functions or classes in the global namespace in Lua.
You can also register into a custom Lua table wrapped in a Object <#part-object>:
object mod = newtable(L);
module(L, mod)
[
// declarations
];
You can then directly use all object manipulation functions on mod.
If you just want to have a namespace for your module (like the standard libraries) you can give a name to the constructor, like this:
module(L, "my_library")
[
// declarations
];
Here all declarations will be put in the my_library table.
If you want nested namespace's you can use the luabind::namespace_ class. It works exactly as luabind::module except that it doesn't take a lua_State* in it's constructor. An example of its usage could look like this:
module(L, "my_library")
[
// declarations
namespace_("detail")
[
// library-private declarations
]
];
As you might have figured out, the following declarations are equivalent:
module(L)
[
namespace_("my_library")
[
// declarations
]
];
module(L, "my_library")
[
// declarations
];
Each declaration must be separated by a comma, like this:
module(L)
[
def("f", &f),
def("g", &g),
class_<A>("A")
.def(constructor<int, int>),
def("h", &h)
];
More about the actual declarations in the Binding functions to Lua <#part-functions> and Binding classes to Lua <#part-classes> sections.
๐ BINDING FUNCTIONS TO LUA ๐
okay bestie, so you wanna let Lua call your C++ functions? you use luabind::def(). here's the synopsis, no cap:
template<class F, class policies>
void def(const char* name, F f, const Policies&);
nameโ the name your function gets inside Lua โจFโ the function pointer you're registeringPoliciesโ this one describes how the parameters and return values get treated by the function. it's optional, so you can skip it. there's a whole Policies section about it, iykyk.
a lil example: say you wanna register float std::sin(float):
module(L)
[
def("sin", &std::sin)
];
๐ฅ Overloaded functions
if you have more than one function with the same name and you want both in Lua, you have to hand over the signature explicitly. it's not you being extra โ C++ literally needs it to know which function you mean. so if you have two functions, int f(const char*) and void f(int):
module(L)
[
def("f", (int(*)(const char*)) &f),
def("f", (void(*)(int)) &f)
];
periodt. ๐
๐ฆ Signature matching
luabind generates code that checks the Lua stack to see whether the values hanging out there can match your function signatures. it'll handle implicit typecasts between derived classes, and it'll prefer the matches with the fewest implicit casts. so if a function is overloaded and no overload matches the parameters better than the others? that's an ambiguity, bestie. and an ambiguity spawns a run-time error telling you the function call is ambiguous. the classic example: register one function taking an int and one taking a float. Lua doesn't distinguish between floats and integers, so both will always match. rip. ๐ญ
since all overloads get tested, it'll always find the best match โ not the first match. and that means it can even handle the situation where the only difference between two signatures is that one member function is const and the other isn't. iconic behaviour honestly.
๐ Ownership transfer
to correctly handle ownership transfer, create_a() would need an adopt return value policy. more on that in the Policies section, go look.
so, example time. if the following function and class is registered:
struct A
{
void f();
void f() const;
};
const A* create_a();
struct B: A {};
struct C: B {};
void g(A*);
void g(B*);
and this Lua code gets executed:
a1 = create_a()
a1:f() -- the const version is called
a2 = A()
a2:f() -- the non-const version is called
a = A()
b = B()
c = C()
g(a) -- calls g(A*)
g(b) -- calls g(B*)
g(c) -- calls g(B*)
see how that works? ๐ซถ
๐ธ Calling Lua functions
to call a Lua function you can either use call_function() or an object. like this:
template<class Ret>
Ret call_function(lua_State* L, const char* name, ...)
template<class Ret>
Ret call_function(object const& obj, ...)
there are two overloads of the call_function function: one that calls a function given its name, and one that takes an object that should be a Lua value you can call as a function.
the overload that takes a name can only call global Lua functions. the ... is a variable number of parameters that get sent to the Lua function. this function call may throw luabind::error if the function call fails. so, y'know, maybe wrap it or don't. ๐
the return value isn't actually Ret (the template parameter), it's a proxy object that will do the function call. this is actually a slay design choice because it enables you to give policies to the call. you do that with the operator[]. you hand over the policies inside the brackets, like this:
int ret = call_function<int>(
L
, "a_lua_function"
, new complex_class()
)[ adopt(_1) ];
if you want to pass a parameter as a reference, you have to wrap it with the Boost.Ref. like this:
int ret = call_function(L, "fun", boost::ref(val));
and if you want a custom error handler for the function call, check out set_pcall_callback under the pcall errorfunc section. โจ
๐ง Using Lua threads
to start a Lua thread you have to call lua_resume(), which means you cannot use the previous call_function() to start a thread, bestie, it's just not the vibe. you have to use:
template<class Ret>
Ret resume_function(lua_State* L, const char* name, ...)
template<class Ret>
Ret resume_function(object const& obj, ...)
and:
template<class Ret>
Ret resume(lua_State* L, ...)
the first time you start the thread, you have to give it a function to execute โ i.e. you have to use resume_function. when the Lua function yields, it will return the first value passed in to lua_yield(). when you want to continue the execution, you just call resume() on your lua_State, and since it's already executing a function, you don't pass it one. the parameters to resume() will be returned by yield() on the Lua side. chef's kiss. ๐
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 yield policy.
with the overload of resume_function that takes an Object, it is important that the object was constructed with the thread as its lua_State*. like this:
lua_State* thread = lua_newthread(L);
object fun = get_global(thread)["my_thread_fun"];
resume_function(fun);
don't skip that part, fr fr. ๐
๐ Binding function objects with explicit signatures
using luabind::tag_function<> it's possible to export function objects from which luabind can't automatically deduce a signature. this can be used to slightly alter the signature of a bound function, or even to bind stateful function objects. so many options.
synopsis:
template <class Signature, class F>
implementation-defined tag_function(F f);
where Signature is a function type describing the signature of F. it can be used like this:
int f(int x);
// alter the signature so that the return value is ignored
def("f", tag_function<void(int)>(f));
struct plus
{
plus(int x)
: x(x)
{}
int operator()(int y) const
{
return x + y;
}
};
// bind a stateful function object
def("plus3", tag_function<int(int)>(plus(3)));
not me being obsessed with tag_function. it's giving flexibility. ๐ฅ
๐ BINDING CLASSES TO LUA ๐
to register classes you use a class called class_. the name is supposed to resemble the C++ keyword, so it looks more intuitive. it has an overloaded member function def() that's used to register member functions, operators, constructors, enums and properties on the class. and โ cute detail โ it returns its this-pointer, so you can chain and register more members directly. main character energy.
let's start with a simple example. consider the following C++ class:
class testclass
{
public:
testclass(const std::string& s): m_string(s) {}
void print_string() { std::cout << m_string << "\n"; }
private:
std::string m_string;
};
to register it with a Lua environment, write as follows (assuming you're using namespace luabind):
module(L)
[
class_<testclass>("testclass")
.def(constructor<const std::string&>())
.def("print_string", &testclass::print_string)
];
this registers the class with the name testclass and a constructor that takes a string as argument, plus one member function named print_string. so gorgeous:
Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> a = testclass('a string')
> a:print_string()
a string
it's 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 visible in Lua, while the object pointer is given as the first parameter. so if we have this C++ code:
struct A
{
int a;
};
int plus(A* o, int v) { return o->a + v; }
you can register plus() as if it was a member function of A like this:
class_<A>("A")
.def("plus", &plus)
plus() can now be called as a member function on A with one parameter, int. and 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). noted. ๐
โญ Overloaded member functions
when binding more than one overload of a member function, or just binding one overload of an overloaded member function, you have to disambiguate the member function pointer you pass to def. to do this you can use an ordinary C-style cast to cast it to the right overload. to do this you have to know how to express member function types in C++ โ here's a short tutorial (for more info, refer to your favorite book on C++). ๐
the syntax for member function pointer follows:
return-value (class-name::*)(arg1-type, arg2-type, ...)
here's an example illustrating this:
struct A
{
void f(int);
void f(int, int);
};
class_<A>()
.def("f", (void(A::*)(int))&A::f)
this selects the first overload of the function f to bind. the second overload is not bound. gone, not invited. ๐
๐ Properties
registering a global data member with a class is easily done. consider the following class:
struct A
{
int a;
};
this class is registered like this:
module(L)
[
class_<A>("A")
.def_readwrite("a", &A::a)
];
this gives read and write access to the member variable A::a. it's also possible to register attributes with read-only access:
module(L)
[
class_<A>("A")
.def_readonly("a", &A::a)
];
when binding members that are a non-primitive type, the auto generated getter function will return a reference to it. this is to allow chained .-operators. for example, when having a struct containing another struct. like this:
struct A { int m; };
struct B { A a; };
when binding B to lua, the following expression code should work:
b = B()
b.a.m = 1
assert(b.a.m == 1)
this requires the first lookup (on a) to return a reference to A, and not a copy. in that case, luabind will automatically use the dependency policy to make the return value dependent on the object in which it's stored. so if the returned reference lives longer than all references to the object (b in this case) it'll keep the object alive, so it doesn't end up being a dangling pointer. protecting you from yourself, we love to see it. ๐ซถโจ
okay so BESTIE, plot twist: you can also register getter and setter functions and make them ~look~ like they're just a public data member. the audacity, the drama, the elegance ๐
check this class:
class A
{
public:
void set_a(int x) { a = x; }
int get_a() const { return a; }
private:
int a;
};
and you can register it as if it had a public data member a, like this:
class_<A>("A")
.property("a", &A::get_a, &A::set_a)
so now whenever someone touches it in Lua, get_a() and set_a() get called instead of just writing straight to the data member. gatekeeping? not here. ๐
want it read only? just omit that last parameter and you're done, iconic behaviour no notes โจ
โ ๏ธ heads up: the get function has to be const, otherwise it won't compile. this is lowkey a common source of errors, so like... double check it, bestie ๐ญ
๐ Enums
if your class has enumerated constants (enums), you can register those too so Lua can see them. but note: they will not be type safe โ all enums are just integers in Lua, and every function that takes an enum will accept any integer you throw at it. no vibe check, no gatekeeping, just ints ๐
you register them like this:
module(L)
[
class_<A>("A")
.enum_("constants")
[
value("my_enum", 4),
value("my_2nd_enum", 7),
value("another_enum", 6)
]
];
in Lua you access them like any data member, except they're read-only and you reach them on the class itself rather than on an instance of the class. main character behaviour tbh ๐
Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> print(A.my_enum)
4
> print(A.another_enum)
6
๐ Operators
to bind operators you have to include <luabind/operator.hpp>. yes, actually include it, don't just manifest it ๐ง
the mechanism is pretty simple honestly. there's a global name luabind::self that refers to the class itself, and then you just write the operator expression inside the def() call. this class:
struct vec
{
vec operator+(int s);
};
is registered like this:
module(L)
[
class_<vec>("vec")
.def(self + int())
];
and this will work regardless of whether your plus operator is defined inside your class or as a free function. no drama either way ๐ซถ
if your operator is const (or, when it's defined as a free function, takes a const reference to the class itself) you have to use const_self instead of self. like this:
module(L)
[
class_<vec>("vec")
.def(const_self + int())
];
the operators you can bind are the ones available in Lua:
+ - * / == < <= %
which means: no in-place operators, sorry babe, that's just the rules.
default implementations (described below, keep reading) are provided for == and the special __tostring pseudo-operator. if any other operator gets called, Luabind will trigger an error: "[const] class <type>: no <metamethod name> defined.", e.g. "class vec: no __div operator defined." ๐
the equality operator (==) has a little hitch โ it will not be called if the references are equal. so your == operator has to do pretty much exactly what it's expected to do. like, actually correct. no shortcuts.
for Luabind's default == operator, two objects are equal only if they're both objects of Luabind-exported classes and have the same addresses, after casting both to a common base if necessary. if they don't have a common base (and aren't of the same type), they compare unequal. periodt.
Lua doesn't support operators like !=, > or >=. that's why you can only register the ones listed above. when you invoke one of the mentioned operators, lua will define it in terms of one of the available operators. iykyk โจ
in the example above, the other operand type is instantiated by writing int(). but if the operand type is a complex type that can't easily be instantiated, you can wrap the type in a class called other<>. for example:
to register this class, we don't want to instantiate a string just to register the operator.
struct vec
{
vec operator+(std::string);
};
instead we use the other<> wrapper like this:
module(L)
[
class_<vec>("vec")
.def(self + other<std::string>())
];
to register an application (function call-) operator:
module(L)
[
class_<vec>("vec")
.def( self(int()) )
];
there's one special operator. in Lua it's called __tostring, and it's not really an operator. it's used for converting objects to strings in a standard way in Lua. if you register this functionality, you'll be able to use the lua standard function tostring() to convert your object to a string. slay ๐
to implement this operator in C++ you should supply an operator<< for std::ostream. like this example:
class number {};
std::ostream& operator<<(std::ostream&, number&);
...
module(L)
[
class_<number>("number")
.def(tostring(self))
];
if you do not define a __tostring operator, Luabind supplies a default which results in strings of the form [const] <type> object: <address>, i.e. const is prepended if the object is const, <type> will be the string you supplied to class_ (or a string derived from std::type_info::name for unnamed classes) and <address> will be the address of the C++ object.
๐ซ note that in multiple inheritance scenarios where the same object is pushed as multiple different base types, the addresses returned for the same most-derived object will differ.
๐ฆ Nested scopes and static functions
it's possible to add nested scopes to a class! super useful when you need to wrap a nested class, or a static function. bestie this is your moment ๐ธ
class_<foo>("foo")
.def(constructor<>())
.scope
[
class_<inner>("nested"),
def("f", &f)
];
in this example, f will behave like a static member function of the class foo, and the class nested will behave like a nested class of foo. mutual โจ
it's also possible to add namespaces to classes using the exact same syntax. same energy, different lore.
๐ Derived classes
if you want to register classes that derive from other classes, you can specify a template parameter bases<> to the class_ instantiation. the following hierarchy:
struct A {};
struct B : A {};
would be registered like this:
module(L)
[
class_<A>("A"),
class_<B, A>("B")
];
if you have multiple inheritance you can specify more than one base. if B would also derive from a class C, it would be registered like this:
module(L)
[
class_<B, bases<A, C> >("B")
];
note that you can omit bases<> when using single inheritance. less typing, we love that for us ๐
Note: if you don't specify that classes derive from each other, luabind will not be able to implicitly cast pointers between the types. so like... actually say it out loud, bestie, luabind can't read your mind ๐ญ
๐ Smart pointers
when registering a class you can tell luabind to hold all instances explicitly created in Lua in a specific smart pointer type, rather than the default raw pointer. this is done by passing an additional template parameter to class_:
class_<X, P>(โฆ)
where the requirements of P are:
- Expression
P(raw)โ returns nothing specified - Expression
get_pointer(p)โ returns something convertible toX*
where:
rawis of typeX*pis an instance ofP
get_pointer() overloads are provided for the smart pointers in Boost, and std::auto_ptr<>. should you need to provide your own overload, note that it is called unqualified and is expected to be found by argument dependent lookup. thus it should be defined in the same namespace as the pointer type it operates on. put it where it belongs, bestie ๐
for example:
class_<X, boost::scoped_ptr<X> >("X")
.def(constructor<>())
will cause luabind to hold any instance created on the Lua side in a boost::scoped_ptr<X>. note that this doesn't mean all instances will be held by a boost::scoped_ptr<X>. if, for example, you register a function:
std::auto_ptr<X> make_X();
the instance returned by that will be held in std::auto_ptr<X>. this is handled automatically for all smart pointers that implement a get_pointer() overload. automatic? we stan ๐
Important:get_const_holder()has been removed. automatic conversions betweensmart_ptr<X>andsmart_ptr<X const>no longer work.
Important: __ok has been removed. similar functionality can be implemented for specific pointer types by doing something along the lines of:
bool is_non_null(std::auto_ptr<X> const& p)
{
return p.get();
}
โฆ
def("is_non_null", &is_non_null)
when registering a hierarchy of classes, where all instances are to be held by a smart pointer, all the classes should have the baseclass' holder type. like this:
module(L)
[
class_<base, boost::shared_ptr<base> >("base")
.def(constructor<>()),
class_<derived, base, boost::shared_ptr<base> >("derived")
.def(constructor<>())
];
internally, luabind will do the necessary conversions on the raw pointers, which are first extracted from the holder type.
this means that for Luabind a smart_ptr<derived> is not related to a smart_ptr<base>, but derived* and base* are, as are smart_ptr<derived> and base*. in other words, upcasting does not work for smart pointers as target types, but as source types. it's giving very specific energy and honestly we respect it ๐
๐ Additional support for shared_ptr and intrusive_ptr
this limitation cannot be removed for all smart pointers in a generic way, but luabind has special support for:
boost::shared_ptrinshared_ptr_converter.hppstd::shared_ptrinstd_shared_ptr_converter.hppboost::intrusive_ptrinintrusive_ptr_converter.hpp
you should include the header(s) you need in the cpp files which register functions that accept the corresponding smart pointer types, to get automatic conversions from smart_ptr<X> to smart_ptr<Y>, whenever Luabind would convert X* to Y*, removing the limitation mentioned above. obsessed, honestly โจ
however, the shared_ptr converters might not behave exactly as you would expect:
- If the
shared_ptrrequested (from C++) has the exact same type as the one which is present in Lua (if any), then a copy will be made. - If the pointee type of the requested
shared_ptrhas ashared_from_thismember (this gets checked automatically at compile time, bestie โจ), then that member is used to obtain ashared_ptr. Caveats tho:- If the object isn't already held in a
shared_ptr, the behavior is undefined โ and honestly it'll probably throw abad_weak_ptrexception at you. ๐ญ - If the
shared_from_thismember is not a function with the right prototype (ptr_t shared_from_this()), with the expression
- If the object isn't already held in a
shared_ptr<RequestedT>(raw->shared_from_this(), raw)
being valid, where raw is of type RequestedT* and points to the C++ object in Lua.
- Otherwise, a fresh new
shared_ptrgets created from the raw pointer that's associated with the Lua object (even if it is not held in ashared_ptr). It gets a deleter set on it that holds a strong reference to the Lua object, which means the object can't be collected until that reference is released by invoking the deleter (i.e. by resetting or destroying theshared_ptr) โ or until the associatedlua_Stategets closed, and at that point theshared_ptrbecomes dangling. ๐
If a shared_ptr like that gets passed back to Lua, the original Lua object (the userdata) is passed instead, which stops more shared_ptrs with this deleter from being created. ๐
- is exactly what you should've expected, and 2. is special behavior that was added so it can dodge 3. whenever possible. If you can't derive your (root) classes from
enable_shared_from_this(which is the recommended way to provide ashared_from_thismethod), then you have to be careful and not close thelua_Statewhile you still have ashared_ptrthat you got through 3. โ ๏ธ
There are three functions provided to help you with this (they live in namespace luabind):
bool is_state_unreferenced(lua_State* L);
typedef void(*state_unreferenced_fun)(lua_State* L);
void set_state_unreferenced_callback(lua_State* L, state_unreferenced_fun cb);
state_unreferenced_fun get_state_unreferenced_callback(lua_State* L);
is_state_unreferenced returns false if closing L would leave existing shared_ptrs dangling, and true if it's safe (in this respect) to call lua_close(L). ๐ซถ
The cb argument you hand to set_state_unreferenced_callback gets called whenever the return value of is_state_unreferenced(L) would flip from false to true. ๐
get_state_unreferenced_callback returns the current state_unreferenced_fun for L.
A typical way to use these functions would be swapping out
lua_close(L);
for
if (luabind::is_state_unreferenced(L))
lua_close(L);
else
luabind::set_state_unreferenced_callback(L, &lua_close);
(lua_close happens to be a valid state_unreferenced_fun, iconic ๐
)
๐ธ Unnamed classes ๐ธ
You can register unnamed classes by just... not passing a name to class_:
class_<X>()
This does not export the class object itself to Lua, which means constructors can't be called and enums are only reachable through objects of this class's type. ๐ซฅ
It's useful for stuff like registering multiple instantiations of a class template and building a matching instance with a factory function โ like boost::make_shared โ or for hiding intermediate classes in inheritance hierarchies. โจ
๐ Splitting class registrations ๐
Sometimes it's just better to split a class registration across different compilation units. Partly to save rebuild time whenever you change one part of the binding, and in some cases compiler limits straight up force you to split it. Doing it is super simple. Look at this sample code:
void register_part1(class_<X>& x)
{
x.def(/*...*/);
}
void register_part2(class_<X>& x)
{
x.def(/*...*/);
}
void register_(lua_State* L)
{
class_<X> x("x");
register_part1(x);
register_part2(x);
module(L) [ x ];
}
Here, the class X is registered in two steps. Those two functions, register_part1 and register_part2, can live in separate compilation units. ๐
If you want to separate the module registration from the classes being registered, go look at Splitting up the registration <#part-split-registration>. ๐ฆ
๐ ADDING CONVERTERS FOR USER DEFINED TYPES ๐
It's possible to get luabind to handle user defined types the same way it handles the built in types, by specializing luabind::default_converter<>:
struct int_wrapper
{
int_wrapper(int value)
: value(value)
{}
int value;
};
namespace luabind
{
template <>
struct default_converter<X>
: native_converter_base<X>
{
static int compute_score(lua_State* L, int index)
{
return lua_type(L, index) == LUA_TNUMBER ? 0 : -1;
}
X from(lua_State* L, int index)
{
return X(lua_tonumber(L, index));
}
void to(lua_State* L, X const& x)
{
lua_pushnumber(L, x.value);
}
};
template <>
struct default_converter<X const&>
: default_converter<X>
{};
}
Quick note bestie: default_converter<> gets instantiated for the actual argument and return types of the bound functions. In the example up there, we add a specialization for X const& that just forwards to the X converter. That's what lets us export functions that accept X by const reference. ๐ฅ
native_converter_base<> should be used as the base class for the specialized converters. It simplifies the converter interface, and it gives you a means for backward compatibility since the underlying interface is in flux. ๐
๐ OBJECT ๐
Okay so like, functions sometimes gotta accept Lua values and those values can be literally any type? Variable type realness. So we wrap them. The wrapper is called luabind::object. If the function you register takes an object, it will match any Lua value. To use it, you need to include <luabind/object.hpp>. Slay.
โจ Synopsis โจ
class object
{
public:
template<class T>
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 safe_bool_type () const;
template<class Key>
implementation-defined operator[](Key const&);
template<class T>
object& operator=(T const&);
object& operator=(object const&);
bool operator==(object const&) const;
bool operator<(object const&) const;
bool operator<=(object const&) const;
bool operator>(object const&) const;
bool operator>=(object const&) const;
bool operator!=(object const&) const;
template <class T>
implementation-defined operator[](T const& key) const
void swap(object&);
implementation-defined operator()();
template<class A0>
implementation-defined operator()(A0 const& a0);
template<class A0, class A1>
implementation-defined operator()(A0 const& a0, A1 const& a1);
/* ... */
};
When you have a Lua object, you can assign it a new value with the assignment operator (=). When you do this, the default_policy will be used to make the conversion from C++ value to Lua. If your luabind::object is a table you can access its members through the operator[] or the Iterators. The value returned from the operator[] is a proxy object that can be used both for reading and writing values into the table (using operator=). Obsessed.
Note that it is impossible to know if a Lua value is indexable or not (lua_gettabledoesn't fail, it succeeds or crashes). This means that if you're trying to index something that cannot be indexed, you're on your own. Lua will call itspanic()function. See lua panic <#sec-lua-panic>.
There are also free functions that can be used for indexing the table, see Related functions.
The constructor that takes a from_stack object is used when you want to initialize the object with a value from the lua stack. The from_stack type has the following constructor:
from_stack(lua_State* L, int index);
The index is an ordinary lua stack index, negative values are indexed from the top of the stack. You use it like this:
object o(from_stack(L, -1));
This will create the object o and copy the value from the top of the lua stack.
The interpreter() function returns the Lua state where this object is stored. If you want to manipulate the object with Lua functions directly you can push it onto the Lua stack by calling push().
The operator== will call lua_compare() on the operands and return its result.
The is_valid() function tells you whether the object has been initialized or not. When created with its default constructor, objects are invalid. To make an object valid, you can assign it a value. If you want to invalidate an object you can simply assign it an invalid object.
The operator safe_bool_type() is equivalent to is_valid(). This means that these snippets are equivalent:
object o;
// ...
if (o)
{
// ...
}
...
object o;
// ...
if (o.is_valid())
{
// ...
}
The application operator will call the value as if it was a function. You can give it any number of parameters (currently the default_policy will be used for the conversion). The returned object refers to the return value (currently only one return value is supported). This operator may throw luabind::error if the function call fails. If you want to specify policies to your function call, you can use index-operator (operator[]) on the function call, and give the policies within the [ and ]. Like this:
my_function_object(
2
, 8
, new my_complex_structure(6)
) [ adopt(_3) ];
This tells luabind to make Lua adopt the ownership and responsibility for the pointer passed in to the lua-function.
It's important that all instances of object have been destructed by the time the Lua state is closed. The object will keep a pointer to the lua state and release its Lua object in its destructor.
Here's an example of how a function can use a table:
void my_function(object const& table)
{
if (type(table) == LUA_TTABLE)
{
table["time"] = std::clock();
table["name"] = std::rand() < 500 ? "unusual" : "usual";
std::cout << object_cast<std::string>(table[5]) << "\n";
}
}
If you take a luabind::object as a parameter to a function, any Lua value will match that parameter. That's why we have to make sure it's a table before we index into it.
std::ostream& operator<<(std::ostream&, object const&);
There's a stream operator that makes it possible to print objects or use boost::lexical_cast to convert it to a string. This will use lua's string conversion function. So if you convert a C++ object with a tostring operator, the stream operator for that type will be used.
๐ฆ Iterators ๐ฆ
There are two kinds of iterators. The normal iterator that will use the metamethod of the object (if there is any) when the value is retrieved. This iterator is simply called luabind::iterator. The other iterator is called luabind::raw_iterator and will bypass the metamethod and give the true contents of the table. They have identical interfaces, which implements the ForwardIterator concept (http://www.sgi.com/tech/stl/ForwardIterator.html). Apart from the members of standard iterators, they have the following members and constructors:
class iterator
{
iterator();
iterator(object const&);
object key() const;
standard iterator members
};
The constructor that takes a luabind::object is actually a template that can be used with object. Passing an object as the parameter to the iterator will construct the iterator to refer to the first element in the object.
The default constructor will initialize the iterator to the one-past-end iterator. This is used to test for the end of the sequence.
The value type of the iterator is an implementation defined proxy type which supports the same operations as luabind::object. Which means that in most cases you can just treat it as an ordinary object. The difference is that any assignments to this proxy will result in the value being inserted at the iterators position, in the table.
The key() member returns the key used by the iterator when indexing the associated Lua table.
An example using iterators:
for (iterator i(globals(L)["a"]), end; i != end; ++i)
{
*i = 1;
}
The iterator named end will be constructed using the default constructor and hence refer to the end of the sequence. This example will simply iterate over the entries in the global table a and set all its values to 1.
๐ง Related functions ๐ง
There are a couple of functions related to objects and tables.
int type(object const&);
This function will return the lua type index of the given object. i.e. LUA_TNIL, LUA_TNUMBER etc.
template<class T, class K>
void settable(object const& o, K const& key, T const& value);
template<class K>
object gettable(object const& o, K const& key);
template<class T, class K>
void rawset(object const& o, K const& key, T const& value);
template<class K>
object rawget(object const& o, K const& key);
These functions are used for indexing into tables. settable and gettable translates into calls to lua_settable and lua_gettable respectively. Which means that you could just as well use the index operator of the object.
rawset and rawget will translate into calls to lua_rawset and lua_rawget respectively. So they will bypass any metamethod and give you the true value of the table entry.
template<class T>
T object_cast<T>(object const&);
template<class T, class Policies>
T object_cast<T>(object const&, Policies);
template<class T>
boost::optional<T> object_cast_nothrow<T>(object const&);
template<class T, class Policies>
boost::optional<T> object_cast_nothrow<T>(object const&, Policies);
The object_cast function casts the value of an object to a C++ value. You can supply a policy to handle the conversion from lua to C++. If the cast cannot be made a cast_failed exception will be thrown. If you have defined LUABIND_NO_ERROR_CHECKING (see Build options <#part-build-options>) no checking will occur, and if the cast is invalid the application may very well crash. The nothrow versions will return an uninitialized boost::optional<T> object, to indicate that the cast could not be performed.
The function signatures of all of the above functions are really templates for the object parameter, but the intention is that you should only pass objects in there, that's why it's left out of the documentation.
object globals(lua_State*);
object registry(lua_State*);
These functions return the global environment table and the registry table respectively.
object newtable(lua_State*);
This function creates a new table and returns it as an object.
object getmetatable(object const& obj);
void setmetatable(object const& obj, object const& metatable);
These functions get and set the metatable of a Lua object.
lua_CFunction tocfunction(object const& value);
template <class T> T* touserdata(object const& value)
These extract values from the object at a lower level than object_cast().
object getupvalue(object const& function, int index);
void setupvalue(object const& function, int index, object const& value);
These get and set the upvalues of function.
๐ธ Assigning nil ๐ธ
To set a table entry to nil, you can use luabind::nil. It will avoid having to take the detour by first assigning nil to an object and then assign that to the table entry. It will simply result in a lua_pushnil() call, instead of copying an object.
Example:
using luabind;
object table = newtable(L);
table["foo"] = "bar";
// now, clear the "foo"-field
table["foo"] = nil;
๐ DEFINING CLASSES IN LUA ๐
So luabind doesn't just let you bind C++ stuff into Lua โ bestie, it also hands you a whole OO-system inside Lua itself. We love to see it. ๐
class 'lua_testclass'
function lua_testclass:__init(name)
self.name = name
end
function lua_testclass:print()
print(self.name)
end
a = lua_testclass('example')
a:print()
And yes, lua-classes can inherit from each other too, because why wouldn't they:
class 'derived' (lua_testclass)
function derived:__init()
lua_testclass.__init(self, 'derived name')
end
function derived:print()
print('Derived:print() -> ')
lua_testclass.print(self)
end
Okay, important detail: the base class gets initialized explicitly, by you calling its __init() function. Nobody's doing it for you, girly. โจ
And like you can see up there, you can totally call the base class's member functions. You can find all the member functions living in the base class, no cap โ but you have to hand them the this-pointer (self) as the first argument. Don't forget it or it's giving ๐.
๐ธ Deriving in lua ๐ธ
You can also flip it: derive Lua classes from C++ classes, and override virtual functions with Lua functions. ๐ฅ To make that happen we gotta create a wrapper class for our C++ base class. That wrapper is the thing that holds the Lua object when we instantiate a Lua class. It's giving main character energy for real.
class base
{
public:
base(const char* s)
{ std::cout << s << "\n"; }
virtual void f(int a)
{ std::cout << "f(" << a << ")\n"; }
};
struct base_wrapper : base, luabind::wrap_base
{
base_wrapper(const char* s)
: base(s)
{}
virtual void f(int a)
{
call<void>("f", a);
}
static void default_f(base* ptr, int a)
{
return ptr->base::f(a);
}
};
// ...
module(L)
[
class_<base, base_wrapper>("base")
.def(constructor<const char*>())
.def("f", &base::f, &base_wrapper::default_f)
];
Important: since MSVC6.5 doesn't support explicit template parameters to member functions, instead of using the member functioncall()you call a free functioncall_member()and pass the this-pointer as first parameter.
Notes, bestie, take them: if you have both base classes and a base class wrapper, you have to give both the bases and the base class wrapper type as template parameter to class_ (like the example above does). The order you list them in? Doesn't matter, slay. ๐ซถ You also have to register both the static version and the virtual version of the function from the wrapper โ that's lowkey necessary so luabind can use both dynamic and static dispatch when calling the function.
Important: it is extremely important that the signatures of the static (default) function are identical to the virtual function. The fact that one of them is a free function and the other a member function doesn't matter at all. But the parameters as seen from lua must match. It would not have worked if the static function took abase_wrapper*as its first argument, since the virtual function takes abase*as its first argument (its this pointer). There's currently no check in luabind to make sure the signatures match. ๐ญ So likeโฆ be careful, okay?
Now, why do we even need the wrapper? If we didn't have a class wrapper, it would not be possible to pass a Lua class back to C++. The entry points of the virtual functions would still point to the C++ base class, and not to the functions defined in Lua. That's exactly why we need one function that calls the base class' real function (used if the lua class doesn't redefine it) and one virtual function that dispatches the call into luabind, letting it pick whether a Lua function should be called, or if the original function should be called. If you don't intend to derive from a C++ class, or if it doesn't have any virtual member functions, you can register it without a class wrapper. Periodt.
You don't need a class wrapper to derive from a class โ but if it has virtual functions you may get silent errors. ๐ Not cute.
The wrappers must derive from luabind::wrap_base. Why? Because it contains a Lua reference that will hold the Lua instance of the object, which is what makes it possible to dispatch virtual function calls into Lua. That dispatch happens through an overloaded member function:
template<class Ret>
Ret call(char const* name, ...)
You use it in a similar way as call_function, except it doesn't take a lua_State pointer, and the name is a member function in the Lua class. ๐
Warning: the current implementation ofcall_memberis not able to distinguishconstmember functions from non-const. If you've got an overloaded virtual function where the only difference in their signatures is their constness, the wrong overload will be called bycall_member. This is rarely the case though. Phew. ๐ฎโ๐จ
Note: you can also override virtual member functions per instance, which often makes it unnecessary to derive a new class in Lua at all. So instead of, like:
class "D" (B)
function D:__init() B.__init(self) end
function D:virtual_function() ... end
you may be able to get around with:
b = B()
function b:virtual_function() ... end
Iconic shortcut, tbh. โจ
๐ฆ Object identity ๐ฆ
When a pointer or reference to a registered class with a wrapper gets passed to Lua, luabind will query for its dynamic type. And if that dynamic type inherits from wrap_base, object identity is preserved. ๐
struct A { .. };
struct A_wrap : A, wrap_base { .. };
A* f(A* ptr) { return ptr; }
module(L)
[
class_<A, A_wrap>("A"),
def("f", &f)
];
> class 'B' (A)
> x = B()
> assert(x == f(x)) -- object identity is preserved when object is
-- passed through C++
Heads up: this functionality relies on RTTI being enabled (meaning LUABIND_NO_RTTI is not defined). No RTTI, no identity, bestie. โจ
๐ Overloading operators ๐
You can overload most operators in Lua for your classes. How? Simply declare a member function with the same name as an operator โ the name of the metamethods in Lua. Obsessed with how easy that is, honestly. The operators you can overload are:
__add__sub__mul__div__pow__lt__le__eq__call__unm__tostring__len
Okay so __tostring isn't really an operator, but it's the metamethod that gets called by the standard library's tostring() function, so it counts. ๐
Now here's one strange behavior regarding binary operators: you are not guaranteed that the self pointer you get actually refers to an instance of your class. Why? Because Lua doesn't distinguish the two cases where you get the other operand as left hand value or right hand value. ๐ญ Consider the following examples:
class 'my_class'
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
This will work well as long as you only subtract 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. No skipping this step, girlie:
function my_class:__sub(v)
if (type(self) == 'number') then
return my_class(self - v.val)
elseif (type(v) == 'number') then
return my_class(self.val - v)
else
-- assume both operands are instances of my_class
return my_class(self.val - v.val)
end
end
The reason __sub is used as the example is because subtraction is not commutative (the order of the operands matters, periodt). That's why luabind cannot just change the order of the operands to make the self reference always refer to the actual class instance. It's giving unavoidable, ngl. ๐ซ
And if you have two different Lua classes with an overloaded operator, the operator of the right hand side type will be called. If the other operand is a C++ class with the same operator overloaded, it will be prioritized over the Lua class' operator. And if none of the C++ overloads matches, then the Lua class operator will be called. โจ
๐ Finalizers ๐
If an object needs to perform actions when it's collected, we provide a __finalize function that can be overridden in lua-classes. The __finalize functions will be called on all classes in the inheritance chain, starting with the most derived type. ๐
...
function lua_testclass:__finalize()
-- called when the an object is collected
end
๐ Slicing ๐
Okay bestie, if your lua C++ classes don't have wrappers (see Deriving in lua ๐) and you derive from them in lua, they may be sliced. Meaning: if an object is passed into C++ as a pointer to its base class, the lua part will be separated from the C++ base part. ๐ This means that if you call virtual functions on that C++ object, they will not be dispatched to the lua class. It also means that if you adopt the object, the lua part will be garbage collected.
+--------------------+
| C++ object | <- ownership of this part is transferred
| | to c++ when adopted
+--------------------+
| lua class instance | <- this part is garbage collected when
| and lua members | instance is adopted, since it cannot
+--------------------+ be held by c++.
The problem can be illustrated by this example:
struct A {};
A* filter_a(A* a) { return a; }
void adopt_a(A* a) { delete a; }
using namespace luabind;
module(L)
[
class_<A>("A"),
def("filter_a", &filter_a),
def("adopt_a", &adopt_a, adopt(_1))
]
And in lua:
a = A()
b = filter_a(a)
adopt_a(b)
In this example, lua cannot know that b actually is the same object as a, and it will therefore consider the object to be owned by the C++ side. So when the b pointer then is adopted, a runtime error will be raised, because an object not owned by lua is being adopted to C++. ๐ Not the vibe.
If you have a wrapper for your class, none of this will happen โ see Object identity. ๐ซถ
๐ EXCEPTIONS ๐
Okay bestie, so here's the tea: if any of the functions you registered throws an exception when it gets called, luabind is gonna catch that exception and convert it into an error string, and then lua_error() gets invoked. ๐ซก
- If the exception is a
std::exceptionor aconst char*, the string that gets pushed onto the Lua stack as the error message will be whateverstd::exception::what()returned, or the string itself, respectively. โจ - If the exception is, like, completely unknown to luabind? It just pushes a generic string saying that the function threw an exception. No further questions. ๐
So if you've got an exception type that isn't derived from std::exception, or you just want to change the error message away from the default what() result โ super valid โ you can register custom exception handlers:
struct my_exception
{};
void translate_my_exception(lua_State* L, my_exception const&)
{
lua_pushstring(L, "my_exception");
}
โฆ
luabind::register_exception_handler<my_exception>(&translate_my_exception);
So translate_my_exception() gets called by luabind every time a my_exception is caught. And heads up: lua_error() is called after the handler function returns, so the expectation is that your function pushes an error string onto the stack. Don't forget it, ok?? ๐
Any function that invokes Lua code may throw luabind::error. What does that mean? It means a Lua run-time error happened. The error message is found on top of the Lua stack. And the reason the exception doesn't just carry the error string around inside itself is because that would require heap allocation, which may fail โ and if an exception class throws an exception while it's being thrown itself, the application will be terminated. ๐ญ So yeah, it's giving "for your own safety."
The synopsis of error is:
class error : public std::exception
{
public:
error(lua_State*);
lua_State* state() const throw();
virtual const char* what() const throw();
};
The state function returns a pointer to the Lua state in which the error was thrown. โ ๏ธ But this pointer may be invalid if you catch this exception after the lua state is destructed. If the Lua state is still valid, you can use it to retrieve the error message from the top of the Lua stack.
An example of where the Lua state pointer may point to an invalid state follows:
struct lua_state
{
lua_state(lua_State* L): m_L(L) {}
~lua_state() { lua_close(m_L); }
operator lua_State*() { return m_L; }
lua_State* m_L;
};
int main()
{
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
/* ... */
}
}
There's another exception that luabind may throw: luabind::cast_failed. This one is thrown from call_function<> or call_member<>. It means that the return value from the Lua function couldn't be converted to a C++ value. It is also thrown from object_cast<> if the cast cannot be made. ๐
The synopsis for luabind::cast_failed is:
class cast_failed : public std::exception
{
public:
cast_failed(lua_State*);
lua_State* state() const throw();
LUABIND_TYPE_INFO info() const throw();
virtual const char* what() const throw();
};
Again, the state member function returns a pointer to the Lua state where the error occurred. See the example above to see where this pointer may be invalid. ๐
The info member function returns the user defined LUABIND_TYPE_INFO, which defaults to a const std::type_info*. This type info describes the type that we tried to cast a Lua value to.
No-exceptions mode!! If you have defined LUABIND_NO_EXCEPTIONS, none of these exceptions will be thrown โ instead you can set two callback functions that get called instead. These two functions are only defined if LUABIND_NO_EXCEPTIONS are defined.
luabind::set_error_callback(void(*)(lua_State*))
The function you set will be called when a runtime-error occurs in Lua code. You can find an error message on top of the Lua stack. This function is not expected to return โ if it does, luabind will call std::terminate(). ๐ณ
luabind::set_cast_failed_callback(void(*)(lua_State*, LUABIND_TYPE_INFO))
The function you set is called instead of throwing cast_failed. This function is also not expected to return โ if it does, luabind will call std::terminate(). ๐
๐ POLICIES ๐
Sometimes you gotta control exactly how luabind passes arguments and return values, and that, bestie, is what policies are for. ๐
All policies use an index to associate them with an argument in the function signature. These indices are result and _N (where N >= 1). And when we're dealing with member functions, _1 refers to the this pointer. Iconic little detail, remember it. โจ
Policies currently implemented ๐
adoptdependencyout_valuepure_out_valuereturn_reference_tocopydiscard_resultreturn_stl_iteratorrawyield
๐ adopt ๐
Motivation
Used to transfer ownership across language boundaries. Handing over the keys, fr fr. ๐
Defined in
#include <luabind/adopt_policy.hpp>
Synopsis
adopt(index)
Parameters
indexโ The index which should transfer ownership,_Norresult.
Example
X* create()
{
return new X;
}
module(L)
[
def("create", &create, adopt(result))
];
๐ฆ dependency ๐ฆ
Motivation
The dependency policy is used to create life-time dependencies between values. This is needed for example when returning internal references to some class. Basically: this one keeps the other one alive so nothing gets yanked out from under you. ๐ซถ
Defined in
#include <luabind/dependency_policy.hpp>
Synopsis
dependency(nurse_index, patient_index)
Parameters
nurse_indexโ The index which will keep the patient alive.patient_indexโ The index which will be kept alive.
Example
struct X
{
B member;
B& get() { return member; }
};
module(L)
[
class_<X>("X")
.def("get", &X::get, dependency(result, _1))
];
๐ธ out_value ๐ธ
Motivation
This policy makes it possible to wrap functions that take non-const references or pointer to non-const as it's parameters, with the intention to write return values to them. And since it's 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). ๐
Defined in
#include <luabind/out_value_policy.hpp>
Synopsis
out_value(index, policies = none)
Parameters
indexโ The index of the parameter to be used as an out parameter.policiesโ The policies used internally to convert the out parameter to/from Lua._1means to C++,_2means from C++.
Example
void f1(float& val) { val = val + 10.f; }
void f2(float* val) { *val = *val + 10.f; }
module(L)
[
def("f", &f, out_value(_1))
];
Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> print(f1(10))
20
> print(f2(10))
20
๐ pure_out_value ๐
Motivation
This works exactly like out_value, except that it will pass a default constructed object instead of converting an argument from Lua. Which means the parameter will be removed from the lua signature. Poof. Gone. โจ
Defined in
#include <luabind/out_value_policy.hpp>
Synopsis
pure_out_value(index, policies = none)
๐ Parameters ๐
okay so here's what you're handing over, bestie:
indexโ the index of the parameter that's gonna be the out parameter ๐policiesโ the policies used internally to convert that out parameter into Lua._1is used as the internal index โจ
๐ธ Example ๐ธ
and like, notice that literally no values are passed to the calls to f1 and f2. the out params just... show up. iconic ๐
void f1(float& val) { val = 10.f; }
void f2(float* val) { *val = 10.f; }
module(L)
[
def("f", &f, pure_out_value(_1))
];
Lua 5.0 Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> print(f1())
10
> print(f2())
10
๐ฆ return_reference_to ๐ฆ
Motivation
so it's super duper common to return references to arguments, or to the this-pointer, so you can chain stuff in C++. like:
struct A
{
float val;
A& set(float v)
{
val = v;
return *this;
}
};
when luabind generates code for this, it makes a whole new object for the return-value, pointing at the self-object. not a problem, but lowkey a little inefficient ๐ฌ. and when you use the return_reference_to policy you get to tell luabind that the return-value is already sitting there on the Lua stack. slay.
Defined in
#include <luabind/return_reference_to_policy.hpp>
Synopsis
return_reference_to(index)
Parameters
indexโ the argument index to return a reference to. any argument but not result ๐ซถ
Example
struct A
{
float val;
A& set(float v)
{
val = v;
return *this;
}
};
module(L)
[
class_<A>("A")
.def(constructor<>())
.def("set", &A::set, return_reference_to(_1))
];
โ ๏ธ Warning: this policy ignores all type information, so only use it in situations where the parameter type is a perfect match for the return-type (like in the example above). no cap, don't get cute with it ๐
โญ copy โญ
Motivation
this one makes a copy of the parameter. and fun fact: this is actually the default behavior when you're passing parameters by-value. note that this can only be used when passing from C++ to Lua. also this policy requires that the parameter type has an accessible copy constructor ๐ง
Defined in
#include <luabind/copy_policy.hpp>
Synopsis
copy(index)
Parameters
indexโ the index to copy.resultwhen used while wrapping C++ functions._Nwhen passing arguments to Lua โจ
Example
X* get()
{
static X instance;
return &instance;
}
module(L)
[
def("create", &create, copy(result))
];
๐ discard_result ๐
Motivation
the simplest little policy ever, fr fr โ it lets you yeet away the value returned by a C++ function instead of converting it to Lua. gone. deleted. bye ๐
Defined in
#include <luabind/discard_result_policy.hpp>
Synopsis
discard_result
Example
struct X
{
X& set(T n)
{
...
return *this;
}
};
module(L)
[
class_<X>("X")
.def("set", &simple::set, discard_result)
];
๐ return_stl_iterator ๐
Motivation
this policy converts an STL container into a generator function you can use in Lua to iterate over the container ๐. it works on any container that defines begin() and end() member functions โ and yeah, those have to return iterators, that part matters ๐
Defined in
#include <luabind/iterator_policy.hpp>
Synopsis
return_stl_iterator
Example
struct X
{
std::vector<std::string> names;
};
module(L)
[
class_<A>("A")
.def_readwrite("names", &X::names, return_stl_iterator)
];
> a = A()
> for name in a.names do
> print(name)
> end
๐ raw ๐
๐ Note:raw()has been deprecated.lua_State*parameters are automatically handled by luabind now. so like, rest in peace queen ๐
Motivation
this converter policy passes through the lua_State* unmodified. super handy for example when you're binding functions that need to return a luabind::object. the parameter gets removed from the function signature, which decreases the function arity by one โจ
Defined in
#include <luabind/raw_policy.hpp>
Synopsis
raw(index)
Parameters
indexโ the index of thelua_State*parameter ๐ซถ
Example
void greet(lua_State* L)
{
lua_pushstring(L, "hello");
}
module(L)
[
def("greet", &greet, raw(_1))
];
> print(greet())
hello
๐ yield ๐
Motivation
makes a C++ function yield when returning. that's it, that's the whole vibe โจ
Defined in
#include <luabind/yield_policy.hpp>
Synopsis
yield
Example
void do_thing_that_takes_time()
{
// ...
}
module(L)
[
def("do_thing_that_takes_time", &do_thing_that_takes_time, yield)
];
๐ SPLITTING UP THE REGISTRATION ๐
bestie, you can absolutely split a module registration across several translation units without making each registration dependent on the module it's being registered in. it's giving โจmodularโจ ๐
a.cpp:
luabind::scope register_a()
{
return
class_<a>("a")
.def("f", &a::f)
;
}
b.cpp:
luabind::scope register_b()
{
return
class_<b>("b")
.def("g", &b::g)
;
}
module_ab.cpp:
luabind::scope register_a();
luabind::scope register_b();
void register_module(lua_State* L)
{
module("b", L)
[
register_a(),
register_b()
];
}
and that's the whole trick, you just declare your scope functions and let the module pull them all together ๐
๐ฅ ERROR HANDLING ๐ฅ
ok bestie, this is the "when it all goes wrong" chapter and honestly it eats ๐ let's get into it.
pcall errorfunc
So, as it says in the Lua documentation over at http://www.lua.org/manual/5.0/manual.html, you can pass an error handler function to lua_pcall(). And here's the tea: luabind calls lua_pcall() internally every time it calls a member function or a free function. So you can set the error handler function that luabind uses, globally:
typedef int(*pcall_callback_fun)(lua_State*);
void set_pcall_callback(pcall_callback_fun fn);
This is mainly useful for stuffing more information into the error message you get back from a failed protected call. For more on how to actually use the pcall_callback function, go look at errfunc under the pcall section of the lua manual: http://www.lua.org/manual/5.0/manual.html#3.15
And if you want to know how to pull debugging information out of lua, that's the debug section of the lua manual: http://www.lua.org/manual/5.0/manual.html#4
The message returned by the pcall_callback is accessible as the top lua value on the stack. So if you want to get at it as a luabind object, you could do something like this:
catch(error& e)
{
object error_msg(from_stack(e.state(), -1));
std::cout << error_msg << std::endl;
}
file and line numbers
Want file name and line number showing up in the error messages luabind gives you? Then write your own pcall errorfunc, bestie ๐ซถ You can absolutely customize this callback to fit your needs, but the basic functionality could look like this:
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;
}
For more on what kind of information you can add to that error message, see the debug section of the lua manual: http://www.lua.org/manual/5.0/manual.html#4
โ ๏ธ heads up: the callback you set withset_pcall_callback()will only be used when luabind executes lua code. Any time you calllua_pcallyourself, you have to supply your function too, if you want error messages translated. no free rides โจ
lua panic
When lua hits a fatal error caused by a bug on the C/C++ side, it calls its internal panic function. This can happen, for example, when you call lua_gettable on a value that isn't a table. If you did the same thing from inside lua, it would of course just fail with an error message instead. ๐
The default panic function will exit() the application. Yes, actually exit. If you want to handle this without your whole application getting taken out, you can define your own panic function using lua_atpanic. The best way to keep going 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 setjmp and longjmp will make sure the stack is correctly unwound. ๐ง
๐ When the panic function is called, the lua state is invalid, and the only allowed operation on it is to close it.
For more information, see the lua manual section 3.19: http://www.lua.org/manual/5.0/manual.html#3.19
structured exceptions (MSVC)
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 lua_error()). Which means, yeah, there's a catch(...) {} in there, lowkey hiding.
In Visual Studio, catch (...) will not only catch C++ exceptions โ it will also catch structured exceptions, like a segmentation fault ๐ So if your function, the one that's getting called from luabind, goes and does an invalid memory addressing, you won't even notice. All that happens is lua hands back an error message saying "unknown exception". iconic in the worst way.
To remedy this, you can create your own exception translator:
void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*)
{ throw; }
#ifdef _MSC_VER
::_set_se_translator(straight_to_debugger);
#endif
This makes structured exceptions, like segmentation fault, actually get caught by the debugger. obsessed ๐
Error messages
These are the error messages that can be generated by luabind, with a more in-depth explanation. Buckle up, bestie, here they come:
the attribute 'class-name.attribute-name' is read only
There is no data member named attribute-name in the class class-name, or there's no setter-function registered on that property name. See the Properties section.
the attribute 'class-name.attribute-name' is of type: (class-name) and does not match (class_name)
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.
class-name() threw an exception, class-name:function-name() threw an exception
The class' constructor or member function threw an unknown exception. Known exceptions are const char*, std::exception. See the Exceptions section.
no overload of 'class-name:function-name' matched the arguments (parameter-types)no match for function call 'function-name' with the parameters (parameter-types)no constructor of class-name matched the arguments (parameter-types)no operator operator-name matched the arguments (parameter-types)
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's no function at all with that name. See the signature matching section.
call of overloaded 'class-name:function-name*(*parameter-types)' is ambiguousambiguous match for function call 'function-name' with the parameters (parameter-types)call of overloaded constructor 'class-name*(*parameter-types)' is ambiguouscall of overloaded operator operator-name (parameter-types) is ambiguous
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. ๐ญ
cannot derive from C++ class 'class-name'. It does not have a wrapped type.
๐ ๏ธ BUILD OPTIONS ๐ ๏ธ
okay bestie, listen UP because this part is literally the make-or-break part ๐
luabind has a whole bunch of configuration options โ they're preprocessor #defines that exist while you're building luabind. and here's the thing that matters more than anything else:
โ ๏ธ your project has to have the exact same configuration options as the ones that were used when the library was built!! literally do not skip this, the whole thing breaks otherwise ๐ญ
the exceptions to that rule are LUABIND_MAX_ARITY and LUABIND_MAX_BASES โ those two are template-based options, so they only matter when you use the library, which means they're allowed to differ from whatever the library itself was built with. slay, love that for them ๐ซถ
to actually pull off the "same options everywhere" thing, you should use the CMake equivalent of these options. and when you build with CMake, the build_information.hpp header gets generated and auto-included by config.hpp, so your options stay in sync all on their own. no cap, it's iconic โจ
๐ the defines ๐
LUABIND_MAX_ARITYโ this one controls the maximum arity of functions you can register with luabind. if your function takes more parameters than this macro's number, you literally cannot register it. default is5, so if your functions are thirstier than that, you gotta redefine it. heads up tho: a high limit = longer compilation time. choose wisely ๐LUABIND_MAX_BASESโ controls the max number of classes one class can derive from in luabind (i.e. how many classes you can put insidebases<>). defaults to4. and yeah, same energy as above: a high limit will increase compilation time โณLUABIND_NO_ERROR_CHECKINGโ if this macro is defined, luabind just... assumes all your Lua code makes legal calls ๐ if illegal function calls happen (like passing params that don't match the function signature), luabind will not detect them and the application will probably crash. so you'd only want to disable error checking when shipping a release build โ and only if no end-user can write custom Lua code. one caveat: function parameter matching still happens if a function is overloaded, because otherwise there's no way to know which one got called. also, functions can still throw exceptions even with error checking disabled. and if a function does throw, luabind catches it and propagates it withlua_error().LUABIND_NO_EXCEPTIONSโ defining this disables all usage oftry,catchandthrowinside luabind. in many cases this kills run-time errors โ like when you're doing invalid casts, or calling Lua functions that fail, or that return values the given policy can't convert ๐ญ. luabind requires that no function called directly or indirectly by luabind throws an exception (throwing exceptions through Lua has undefined behavior โ like, do not). where exceptions were the only way luabind could report an error to you, they get replaced with calls to the callback functions set withset_error_callback()andset_cast_failed_callback().LUA_APIโ wanna link dynamically against Lua? set this define to the import-keyword for your compiler and platform. on Windows in Visual Studio it should be__declspec(dllimport)if you want to link against Lua as a dll.LUABIND_DYNAMIC_LINKโ must be defined if you plan to link against the luabind shared library (.soor DLL) or build it as such. and ngl, in future versions of luabind this option may end up depending onBUILD_SHARED_LIBSin CMake โ so just always set both CMake options to the same value, okay? ๐ if you enable this, you should link Lua dynamically to both Luabind and your application. if you start seeing double-free errors or other memory corruption, this is very possibly the culprit. good luck bestie ๐LUABIND_CPLUSPLUS_LUAโ without this, all included Lua headers get wrapped inextern "C". define it if you compiled Lua as C++.NDEBUGโ this define disables all asserts and should be defined in a release build. periodt.LUABIND_USE_NOEXCEPTโ if you useBoost <= 1.46but your compiler is C++11 compliant and marks destructors asnoexceptby default, you need to defineLUABIND_USE_NOEXCEPT. failing to do this will causestd::terminate()to be called if a destructor throws (e.g. the destructor of the proxy returned bycall_functionorobject::operator()) ๐๐LUABIND_LIBRARY_VERSIONโ specify the version of luabind being built, inx.y.zform.
๐ CMake options ๐
these are the options you can hand to CMake when building luabind. you can either specify them right on the commandline with -Doption=value, or let CMake ask you about each one by invoking it with the -i flag. on Windows you'll usually wanna use cmake-gui instead ๐ฅ๏ธโจ
all options are booleans, unless specified otherwise.
LUABIND_ENABLE_WARNINGSโ enable compiler warnings during the build of luabind and the tests.LUABIND_USE_CXX11โ controls whether the-std=c++11flag is passed to compilers that support it. and also whether support for C++11 scoped enums can be enabled ๐BUILD_TESTINGโ whether to generate build files for the unit tests (they must be run manually in any case, so don't @ me).LUABIND_BUILD_HEADER_TESTSโ enable this for (many) additional compilation tests: each of Luabind's public headers gets included in a generated.cppfile that otherwise contains nothing but an emptymainfunction โ meaning one dummy binary per header file gets generated ๐ง this can only be enabled ifBUILD_TESTINGis enabled.LUABIND_APPEND_VERSION_SUFFIXโ with this option set (the default), built binaries and object archives get named like e.g.luabind09.dllinstead of justluabind.dll. cute โจLUABIND_LUA_VERSIONโ a string variable that defaults to""(the empty string). it can be set to"51"or"52"to use the respective Lua versions. if you leave it empty, Lua52 gets tried first before falling back to Lua51.CMAKE_BUILD_TYPEโ string option. go peek at the corresponding entry in the CMake manual, bestie ๐
๐ง IMPLEMENTATION NOTES ๐ง
so the classes and objects are implemented as user data in Lua. and to make sure that user data really is the internal structure it's supposed to be, we tag their metatables ๐ท๏ธ previously a boolean at a string key was used, which made it relatively easy for a malevolent user to fool Luabind and crash the application. rude. but that's been replaced with a light userdata key that should be pretty much impossible to imitate ๐
in the Lua registry, luabind kept an entry called "__luabind_classes". this string key is now also replaced with a light userdata one. glow-up tbh ๐
in the global table, a variable called super is used every time a constructor in a lua-class is called. why? to make it easy for that constructor to call its base class' constructor. so yeah โ if you have a global variable named super it may get overwritten ๐ this is probably not the best solution, and this restriction may be removed in the future.
Note: Deprecatedsuper()has been deprecated since version 0.8 in favor of directly invoking the base class'__init()function:function Derived:__init() Base.__init(self) end
๐ The detail namespace and undocumented features ๐
inside the luabind namespace there's another namespace called detail. everything contained in there should not be used by user code, and it's subject to change or vanish even between patch versions ๐ญ there also exist no explicit tests or documentation for this namespace's contents. so like... it's giving forbidden knowledge.
classes and functions that live directly in the luabind namespace but aren't documented should also rather not be used. but hey โ if you absolutely have to depend on undocumented features, those are still better than the detail ones. pick your chaos wisely bestie ๐
๐ FAQ ๐
What's up with __cdecl and __stdcall?
okay so if you're getting problems with functions that cannot be converted from void (__stdcall *)(int,int) to void (__cdecl*)(int,int), bestie, that's the calling convention beefing with itself. You can change the project settings so the compiler generates functions with __cdecl calling conventions. This is a problem in developer studio. โจ
What's wrong with functions taking variable number of arguments?
You literally cannot register a function with ellipses in its signature. And honestly? Since ellipses don't preserve type safety, those should be avoided anyway. It's giving unsafe. ๐
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 Splitting up the registration and Splitting class registrations. ๐ธ
What's wrong with precompiled headers in VC?
Visual Studio doesn't like anonymous namespaces in its precompiled headers. Not the vibe. If you encounter this problem you can disable precompiled headers for the compilation unit (cpp-file) that uses luabind.
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. ๐ฅ
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).
How come my executable is huge?
If you're 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.
Our tests suggests that cygwin's gcc produces much bigger executables compared to gcc on other platforms and other compilers. ๐
Can I register class templates with luabind?
Yes you can, but you can only register explicit instantiations of the class. Because there's no Lua counterpart to C++ templates. For example, you can register an explicit instantiation of std::vector<> like this:
module(L)
[
class_<std::vector<int> >("vector")
.def(constructor<int>)
.def("push_back", &std::vector<int>::push_back)
];
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.
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).
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. ๐ซถ
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).
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 out_value and pure_out_value policies. ๐
๐ฆ KNOWN ISSUES ๐ฆ
- You cannot use strings with extra nulls in them as member names that refers to C++ members.
- If one class registers two functions with the same name and the same signature, there's currently no error. The last registered function will be the one that's used.
- In VC7, classes can not be called
test. - If you register a function and later rename it, error messages will use the original function name.
- luabind does not support class hierarchies with virtual inheritance. Casts are done with static pointer offsets.
๐ ACKNOWLEDGMENTS ๐
Written by Daniel Wallin and Arvid Norberg. ยฉ Copyright 2003. All rights reserved.
Evan Wies has contributed with thorough testing, countless bug reports and feature ideas.
Many features and fixes of this fork come from Ryan Pavlik's (rpavlik) fork https://github.com/rpavlik/luabind/ and from Peter Colberg (fhoefling's fork) https://github.com/fhoefling/luaponte/.
Christian Neumรผller (Oberon00) is the maintainer of this fork http://github.com/Oberon00/luabind/.
A rather complete list of contributors can be found at http://github.com/Oberon00/luabind/contributors.
This library was highly inspired by Dave Abrahams' Boost.Python http://www.boost.org/libs/python library.
- Search Page <>
๐ Author ๐
Daniel Wallin, Arvid Norberg
๐ Copyright ๐
2005 Rasterbar Software; 2013 Christian Neumรผller
and that's the whole page, bestie!! ๐ฅณ you made it all the way through luabind(3), every last FAQ and every last contributor, no cap. this manual is for version 0.9, dated Oct 14, 2026, and it's the LUABIND(3) page โ so if you ever need to cite it, that's the deets. go forth and bind your C++ to Lua, you absolute icon, i'm so proud of you ๐โจ๐ฆ๐
๐ฆ where this page comes from
- ubuntu stonking: libluabind-dev 1.1.1-1ubuntu1 ยท MIT OR BSL-1.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms