Working with LUA and C++

LUA is a small scripting language designed to be embedded inside your application to provide extensibility.

Weighting in at less than 200k and being small, fast, and reliable it is an ideal choice for providing a built-in scripting language to your applications.

However one potential drawback is that it is written in C.

This page contains a simple example of wrapping and using LUA from C++ code in a simple manner.

Taking advantage of the "Singleton Design Pattern" it wraps an intepretter object into a single C++ class, CLUAInstance and demonstrates how it could be used.

Sample Usage

Calling a simple script "lua.lua" from a C++ application might look like this:

#include "luainstance.h"

int main( int argc, char *argv[] )
  int ret = -1;

   * Gain access to the single LUA intepretter object.
  CLUAInstance *lua = CLUAInstance::getInstance();

   * Run a script with it!
  lua->runScript( "lua.lua" );

   * Call a function defined in the LUA script.
  lua->callFunction( "test", "si>i", "string parameter", 2, &ret );
  printf("Function returned: %d\n", ret );

   * Cleanup.
  delete( lua );

The CLUAInstance class makes two new functions available to the lua scripts you run:

  • getenv
  • system

So a sample script "lua.lua" could look like this:

print( "Your home directory is " .. getenv( "HOME" ) );
system( "/usr/bin/emacs" );

(Note: both of these functions are already available to LUA scripts via "os.execute", and "os.getenv", respectively. They are included as simple demonstrations only)


You can download the tarball from the following link, or just explore the source directory.


To compile this code you'll need the LUA 5.0 development files already installed upon your system.

On a Debian host you can fetch the files with the following command:

apt-get install liblualib50-dev liblua50-dev