the language, I’ll demonstrate how Lua variables and functions can be
accessed from within C++ and vice versa. We’ll then spend some time
examining how C++ classes can be exposed to Lua before moving on to a
little project that ties everything together.
NOTE Although this chapter will show you enough to get you started, it’s
impossible to do the language justice in just one chapter. Therefore, I highly rec
ommend you read the Lua documentation and visit the Lua user’s wiki online at
Lua comes with an interactive interpreter (common/lua-5.0/bin/lua.exe)
you can use to try out little snippets of code by typing them directly into
the console at the command prompt, but for anything more than a couple of
lines you may find this tedious. I think the best way to start your journey
into Lua is by showing you how to run a script using the C/C++ Lua API.
This way you can use the familiar environment of your compiler’s IDE to
write and run scripts.
Let me talk you through the code required to run a Lua script from a
First you have to include the relevant header files. Since Lua is a pure C
library, you must let the compiler know this explicitly or you’ll experience
problems. This is done by encasing the
#includes with extern “C”.
//include the lua libraries. If your compiler doesn't support this pragma
//then don't forget to add the libraries in your project settings!
#pragma comment(lib, "lua.lib")
#pragma comment(lib, "lualib.lib")
//create a lua state
lua_State* pL = lua_open();
Each script file you run will be executed in a dynamically allocated struc
ture called a
lua_State. Every function in the Lua library requires that a
pointer to a
lua_State be passed to it as a parameter. Therefore, before run
ning a script file you must create a Lua state by calling
//enable access to the standard libraries
To Script, or Not to Script, That Is the Question
Scripting in Lua