tolua++ - Reference Manual

by Waldemar Celes, Ariel Manzur.


tolua++ is an extended version of tolua, a tool to integrate C/C++ code with Lua. tolua++ includes new features oriented to c++ such as:

As well as other features and bugfixes.

tolua is a tool that greatly simplifies the integration of C/C++ code with Lua. Based on a cleaned header file (or extracts from real header files), tolua automatically generates the binding code to access C/C++ features from Lua. Using Lua API and tag method facilities, tolua maps C/C++ constants, external variables, functions, classes, and methods to Lua.

This manual is for tolua++ version 1.0 and is implemented upon Lua 5.0 and based on tolua 5.0. See Compatibility for details on switching from older versions.

The sections below describe how to use tolua. Please contact us with bug reports, suggestions, and comments.


How tolua works

To use tolua, we create a package file, a C/C++ cleaned header file, listing the constants, variables, functions, classes, and methods we want to export to the Lua environment. Then tolua parses this file and creates a C/C++ file that automatically binds the C/C++ code to Lua. If we link the created file with our application, the specified C/C++ code can be accessed from Lua.
A package file can also include regular header files, other package files, or lua files.

Let's start with some examples. If we specify as input the following C-like header file to tolua:

#define FALSE 0
#define TRUE 1

enum { 
 POINT = 100, 
 LINE, 
 POLYGON
}
Object* createObejct (int type);
void drawObject (Object* obj, double red, double green, double blue);
int isSelected (Object* obj);
A C file that binds such a code to Lua is automatically generated. Therefore, in Lua code, we can access the C code, writing, for instance:
...
myLine = createObject(LINE)
...
if isSelected(myLine) == TRUE then
  drawObject(myLine, 1.0, 0.0, 0.0);
else
  drawObject(myLine, 1.0, 1.0, 1.0);
end
...
Also, consider a C++-like header file:
#define FALSE 0
#define TRUE 1
class Shape
{
  void draw (void);
  void draw (double red, double green, double blue);
  int isSelected (void);
};
class Line : public Shape
{
 Line (double x1, double y1, double x2, double y2);
 ~Line (void);
};
If this file is used as input to tolua, a C++ file is automatically generated proving access to such a code from Lua. Therefore, it would be valid to write Lua statements like:
...
myLine = Line:new (0,0,1,1)
...
if myLine:isSelected() == TRUE then
 myLine:draw(1.0,0.0,0.0)
else
 myLine:draw()
end
...
myLine:delete()
...
The package file (usually with extension .pkg) passed to tolua is not the real C/C++ header file, but a cleaned version of it. tolua does not implement a complete parse to interpret C/C++ code, but it understands a few declarations that are used to describe the features that are to be exported to Lua. Regular header files can be included into packages files; tolua will extract the code specified by the user to parse from the header (see Basic Concepts).

How to use toLua

tolua is composed by two pieces of code: an executable and a library. The executable represents the parser that reads a package file and output a C/C++ code that implements the binding to access the C/C++ features from Lua. If the package file is a C++ like code (i.e., includes class definitions), a C++ code is generated. If the cleaned header file is a C like code (i.e., without classes), a C code is generated. tolua accepts a set of options. Running "tolua -h" displays the current accepted options. For instance, to parse a file called myfile.pkg generating the binding code in myfile.c, we do:

tolua -o myfile.c myfile.pkg

The generated code must be compiled and linked with the application to provide the desired access from Lua. Each parsed file represents a package being exported to Lua. By default, the package name is the input file root name (myfile in the example). The user can specify a different name for the package:

tolua -n pkgname -o myfile.c myfile.pkg

The package should also be explicitly initialized. To initialize the package from our C/C++ code, we must declare and call the initialization function. The initialization function is defined as

int tolua_pkgname_open (lua_State*);

where pkgname represents the name of the package being bound. If we are using C++, we can opt for automatic initialization:

tolua -a -n pkgname -o myfile.c myfile.pkg

In that case, the initialization function is automatically called. However, if we are planning to use multiple Lua states, automatic initialization does not work, because the order static variables are initialized in C++ is not defined.

Optionally, the prototype of the open function can be outputted to a header file, which name is given by the -H option.

The binding code generated by tolua uses a set of functions defined in the tolua library. Thus, this library also has to be linked with the application. The file tolua.h is also necessary to compile the generated code.

An application can use tolua object oriented framework (see exported utility functions) without binding any package. In that case, the application must call tolua initialization function (this function is called by any package file initialization function):

int tolua_open (void);

Basic Concepts

The first step in using tolua is to create the package file. Starting with the real header files, we clean them by declaring the features we want to access from Lua in a format that tolua can understand. The format tolua understands is simple C/C++ declarations as described below.

Including files

A package file may include other package file. The general format to do that is:

$pfile "include_file"

A package file may also include regular C/C++ header files, using the hfile or cfile directive:

$cfile "example.h"

In which case, tolua will extract the code enclosed between tolua_begin and tolua_end, or or tolua_export for a single line. Consider this C++ header as example:


#ifndef EXAMPLE_H
#define EXAMPLE_H

class Example { // tolua_export

private:

	string name;
	int number;

public:

	void set_number(int number);

	//tolua_begin

	string get_name();
	int get_number();
};
// tolua_end

#endif

In this case, the code that's not supported by tolua (the private part of the class), along with the function set_number is left outside of the package that includes this header.

Finally, lua files can be included on a package file, using $lfile:

$lfile "example.lua"

New on tolua++: an extra way to include source files is available since version 1.0.4 of tolua++, using ifile:

$ifile "filename"

ifile also takes extra optional parameters after the filename, for example:

$ifile "widget.h", GUI
$ifile "vector.h", math, 3d

ifile's default behaviour is to include the whole file, untouched. However, the contents of the file and the extra parameters are put through the include_file_hook function before being included into the package (see Customizing tolua++ for more details).

Basic types

tolua automatically maps C/C++ basic types to Lua basic types. Thus, char, int, float, and double are mapped to the Lua type number; char* is mapped to string; and void* is mapped to userdata. Types may be preceded by modifiers (unsigned, static, short, const, etc.); however, be aware that tolua ignores the modifier const if applied to basic types. Thus, if we pass a constant basic type to Lua and then pass it back to C/C++ code where a non constant is expected, the constant to non constant conversion will be silently done.

Functions in C/C++ can also manipulate Lua objects explicitly. Thus lua_Object is also considered a basic type. In this case, any Lua value matches it.

New on tolua++: The C++ type string is also considered a basic type, and is passed as a value to lua (using the c_str() method). This feature can be turned off with the command line option -S.

User defined types

All other types that appear in the package file being processed are considered user defined types. These are mapped to tagged userdata type in Lua. Lua can only store pointers to user defined types; although, tolua automatically makes the necessary arrangement to deal with references and values. For instance, if a function or method returns a value of user defined type, tolua allocates a clone object when returning it to Lua and sets the garbage collection tag method to automatically free the allocated object when no longer in use by Lua.

For user defined types, constness is preserved. Thus passing a non constant user defined type to a function that expects constant type generates an type mismatching error.

NULL and nil

C/C++ NULL or 0 pointers are mapped to Lua nil type; conversely, nil may be specified wherever a C/C++ pointer is expected. This is valid for any type: char*, void*, and pointers to user defined types.

Typedefs

tolua also accepts simple typedef's inside the package files. Any occurrence of a type after its definition is mapped by tolua to the base type. They are useful because several packages redefine the basic C/C++ types to their own types. For instance, one can define the type real to represent a double. In that case, real can be used to specify the variable types inside the package file interpreted by tolua, but only if we include the following definition before any use of the type real.

typedef double real;

Otherwise, real would be interpreted as a user defined type and would not be mapped to Lua numbers.

Including real header files

In the package file, we must specify which are the real header files that should be included so that the generated code can access the constants, variables, functions, and classes we are binding. Any line in the package file beginning with a $ (except $[hclp]file, $[ , and $] lines) is inserted into the generated binding C/C++ code without any change, but the elimination of the $ itself. We use this feature to include the real header files. So, our package files will usually start with a set of $ beginning lines specifying the files that must be included, that is, the files the package file is based on.
/* specify the files to be included */
$#include "header1.h"                 // include first header
$#include "header2.h"                 // include second header
As illustrated, tolua also accepts comments, using C or C++ convention, inside the package file. Nested C-like comments can also be used.

Also note that files included with $cfile or $hfile don't need to be included using this method, this is done automatically by tolua.

In the following sections, we describe how to specify the C/C++ code we want to bind to Lua. The formats are simplified valid C/C++ statements.

Binding constants

To bind constants, tolua accepts both define's and enum's. For define's the general format is:
#define NAME [ VALUE ]
The value, as showed above, is optional. If such a code is inserted inside the file being processed, tolua generates a code that allows the use of NAME as a Lua global variable that has the corresponding C/C++ constant value. Only numeric constants are accepted.

New on tolua++: All other preprocessor directives are ignored.

For enum's, the general format is:

enum {
  NAME1 [ = VALUE1 ] ,
  NAME2 [ = VALUE2 ] ,
  ...
  NAMEn [ = VALUEn ]
};
Similarly, tolua creates a set of global variables, named NAMEi, with their corresponding values.

Binding external variables

Global extern variables can also be exported. In the cleaned header file they are specified as:
[extern] type var;
tolua binds such declarations to Lua global variables. Thus, in Lua, we can access the C/C++ variable naturally. If the variable is non constant, we can also assign the variable a new value from Lua. Global variables that represent arrays of value can also be bound to Lua. Arrays can be of any type. The corresponding Lua objects for arrays are Lua tables indexed with numeric values; however, be aware that index 1 in Lua is mapped to index 0 in an C/C++ array. Arrays must be pre dimensioned. For instance:

double v[10];

New on tolua++: External variables can use the tolua_readonly modifier (see Additional Features)

Binding functions

Functions are also specified as conventional C/C++ declarations:
type funcname (type1 par1[, type2 par2[,...typeN parN]]);
The returned type can be void, meaning no value is returned. A function can also have no parameter. In that case, void may be specified in the place of the list of parameters. The parameter types must follow the rules already posted. tolua creates a Lua function binding the C/C++ function. When calling a function from Lua, the parameter types must match the corresponding C/C++ types, otherwise, tolua generates an error and reports which parameter is wrongly specified. If a parameter name is omitted, tolua names it automatically, but its type should be a basic type or user type previously used.

Arrays

tolua also deals with function or method parameters that represent arrays of values. The nice thing about arrays is that the corresponding Lua tables have their values updated if the C/C++ function changes the array contents.

The arrays must be pre dimensioned. For instance:

void func (double a[3]);

is a valid function declaration for tolua and calling this function from Lua would be done by, for instance:

p = {1.0,1.5,8.6}
func (p)

The array dimension need not be a constant expression; the dimension can also be specified by any expression that can be evaluated in run time. For instance:

void func (int n, int m, double image[n*m]);

is also valid since the expression n*m is valid in the binding function scope. However, be aware that tolua uses dynamic allocation for binding this function, what can degrade the performance.

Despite the dimension specification, it is important to know that all arrays passed to the actual C/C++ function are in the local scope of the binding function. So, if the C/C++ function being called needs to hold the array pointer for later use, the binding code will not work properly.

Overloaded functions

Overloaded functions are accepted. Remember that the distinction between two functions with the same name is made based on the parameter types that are mapped to Lua. So, although

void func (int a);
void func (double a);

represent two different functions in C++, they are the same function for tolua, because both int and double are mapped to the same Lua type: number.

Another tricky situation occurs when expecting pointers. Suppose:

void func (char* s);
void func (void* p);
void func (Object1* ptr);
void func (Object2* prt);
Although these four functions represent different functions in C++, a Lua statement like:
func(nil)
matches all of them.

It is important to know that tolua decides which function will be called in run-time, trying to match each provided function. tolua first tries to call the last specified function; if it fails, tolua then tries the previous one. This process is repeated until one function matches the calling code or the first function is reached. For that reason, the mismatching error message, when it occurs, is based on the first function specification. When performance is important, we can specify the most used function as the last one, because it will be tried first.

tolua allows the use of overloaded functions in C, see Renaming for details.

Default parameter values

The last function parameters can have associated default values. In that case, if the function is called with fewer parameters, the default values are assumed. The format to specify