NOTE Unlike C++, Lua handles memory management automatically. It uses
something called a garbage collector to periodically delete all the dead objects.
The performance of the garbage collector can be customized to your taste,
ranging from immediate deletion of dead objects to no deletion. See the Lua
documentation for further details.
Exposing a C/C++ Class to Lua
This is where things start to get tricky! Exposing a C++ class to a Lua
script can be pretty gnarly. You basically have to create a Lua table that has
as its elements the class data and methods you require to expose. You may
also have to create a metatable that defines how your class behaves with
any appropriate operators such as == or *. As you have seen, simply expos
ing a C-like function to Lua can get longwinded, so you can imagine the
amount of work required to expose a C++ class. Fortunately, someone has
already done the hard work for us and created an API allowing for
pain-free class (and function) registration. It’s called Luabind, and just like
Lua it’s free, open-source, and easy to use and understand.
Luabind to the Rescue!
Luabind is a library for creating bindings between Lua and C++. It is
implemented using the magic of template meta-programming so the source
code is not for the faint hearted, but it makes exposing your C/C++ classes
and functions a cinch. It handles inheritance and templated classes and you
can even use it to create classes in Lua. It’s still in the early days of devel-
opment, so it is not without its problems, but these are few and the
developers, Daniel Wallin and Arvid Norberg, have put in a lot of time to
iron out the bugs and to provide fast and helpful support should you need
Setting Up Luabind
Before you can use Luabind you must set up your compiler correctly.
Luabind (6.0) requires you to have the Boost library 1.30.0 or later headers
installed. You can download Boost from www.boost.org. Unzip and add the
boost header folder to your compiler’s include paths.
The required files for Luabind are in the folder common/luabind. You
must set this path in your compiler for the Luabind headers, and the path
common/luabind/src for the source files. Although you can build the
Luabind libraries, it’s much easier (unless you are using UNIX) to just
include all the files found in common/luabind/src in your project.
TIP For those of you who use .NET, there is a Lua and Luabind .NET wrapper
called LuaDotNet available from codeproject. You can grab it from:
276 | Chapter 6
Scripting in Lua