Thursday, July 17, 2008

Lua - Scripting Language

More info on Lua available at About - Lua.

Here we will see how we can call lua script from C++. Code below is tested with VC2K5 EE with Lua 5.1.

#include

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

class Lua_State
{
lua_State *L;
public:
Lua_State() : L(lua_open()) { }

~Lua_State() {
lua_close(L);
}

// implicitly act as a lua_State pointer
inline operator lua_State*() {
return L;
}
};

static void open_libs(lua_State *L)
{
luaL_openlibs(L); // Lua 5.1 single call to load all libs
}

static int execute_program(lua_State *L)
{
// make a short function to make program behaviour more clear
return lua_pcall(L, 0, LUA_MULTRET, 0);
}

static void report_errors(lua_State *L, const int status)
{
if ( status!=0 ) {
std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1); // remove error message
}
}

int main(int argc, char** argv)
{
for ( int n=1; n
Lua_State L;
open_libs(L);

int s = luaL_loadfile(L, argv[n]);

if ( s==0 )
s = execute_program(L);

report_errors(L, s);

// lua_close(L) automatically called here
}

int i;
std::cin >> i;
return 0;
}


Additional library required to build is luaX.Y.lib where X and Y refers to lua version. I had this as lua5.1.lib.

This is the simple way to use/call lua from C++. More useful/handy examples available at SampleCode.