Lua is a very lightweight language to be embedded as a scripting support language for any system.
Following are the steps to embed Lua engine in C/C++.
Step 1. Include header files.
extern "C" {
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
}
Step 2. Initialize Lua engine
lua_State *engine = lua_open();
luaopen_base(engine);
luaopen_string(engine);
luaopen_math(engine);
luaopen_table(engine);
/* above luaopen_* can be replaced with luaL_openlibs(engine) to open all standard libraries */
Step 3. Load Lua script from buffer
char *buf;
// read script into buffer
if (luaL_loadbuffer(engine, buf, strlen(buf) != LUA_OK) {
fprintf(stderr, "loading script failed with error %s", lua_tostring(engine, -1));
lua_pop(engine, 1);
// do not continue
}
Step 4. Execute the loaded buffer
if (lua_pcall(engine
, 0 // number of arguments on the stack
, 0 // number of expected result parameters
, 0) != LUA_OK) {
fprintf(stderr, "executing script failed with error %s", lua_tostring(engine, -1));
lua_pop(engine, 1);
// do not continue
}
More about lua_pcall
Step 5. Register C function to be called within Lua script
// following function can be called from Lua script with 1 parameter
int add_ten(lua_State *engine) {
double p = lua_tonumber(engine, 1);
p = p + 10.0;
lua_pushnumber(engine, p);
return 1;
}
lua_register(engine, "add_ten", add_ten);
// call add_ten within engine
lua_getglobal(engine, "add_ten");
lua_pushnumber(engine, 50.0);
lua_call(engine, 1, 1); // pass one parameter and get back 1 parameter
double result = lua_tonumber(engine, -1); // fetch from top of stack
printf( "result = %g\n", result ); // this should print 60
Step 6. Destroy Lua engine
lua_close(engine);