Using LUA in a C++, Visual Studio 2013, Qt, or any C/C++ application

Start Super-Quick-Start Guide:

  1. Download and extract the LUA source.  Click here
  2. Add all of the .c files in the “src” directory to your project except for lua.c and luac.c (these are the interpreter and compiler that are not needed for this example and, depending on your use, are not needed at all)
  3. Add the path to the LUA headers to your project include paths. For example:
    “lua-5.3.1/src”
  4. Assuming you are using C++, add this line to the top of your source to include the headers needed in a C++ friendly way:
    #include “lua.hpp”
  5. That is it!  You are all set and ready to use LUA in your program.
  6. OK, here is an example to get you started!
const char* luaScript = "\
addCount=0\n\
\n\
function addTwoNumbers(x,y)\n\
  addCount = addCount + 1\n\
  return (x+y)\n\
end\n\
\n";
int luaScriptLength = strlen(luaScript);
int addCount;
int addResult;

// create lua and load the script data
lua_State *L = 0;
L = luaL_newstate();
luaL_loadbuffer(L, luaScript, luaScriptLength, "luaScript");
lua_pcall(L, 0, 0, 0);

// get value of addCount global variable
// stack addCount
lua_getglobal(L, "addCount");
// value of top stack item (in this case addCount)
addCount = lua_tointeger(L, -1);
// addCount should be 0
// unstack var1
lua_pop(L, 1);

// add two numbers
// stack addTwoNumbers
lua_getglobal(L, "addTwoNumbers");
// stack value 5
lua_pushinteger(L, 5);
// stack value 10
lua_pushinteger(L, 10);
// call 2 stacked args, 1 stacked function, and expect 1 stack result
lua_pcall(L, 2, 1, 0);
// value of top stack item (in this case the addTwoNumbers result)
addResult = lua_tointeger(L, -1);
// addResult should be 15
// unstack result
lua_pop(L, 1);

// get value of addCount global variable
// stack addCount
lua_getglobal(L, "addCount");
// value of top stack item (in this case addCount)
addCount = lua_tointeger(L, -1);
// addCount should be 1
// unstack addCount
lua_pop(L, 1);

lua_close(L);

Author: sirspot

I write software, love my wife and kids, do various house projects, play video games when I have time, and could use a little more sleep