Game Development Reference
In-Depth Information
Unfortunately, I don
t have the page count to go in-depth into LuaPlus. This will be a
whirlwind tour of what it has to offer. Hang on!
'
Everything in Lua begins with the Lua state. The Lua state represents an execution envi-
ronment for Lua. You can have as many states as you want; each will be totally separate
with its own set of global variables, functions, etc. There are many reasons you might
want multiple states. One example might be allowing each C++ thread to have its own
state. For the purposes of this topic, we only create a single state for the program.
In the Lua C API, the
lua_State struct
contains all the data necessary to access
the state. Nearly all Lua functions require the
lua_State
object as their first param-
eter. This looks suspiciously like C trying to act like C++, doesn
'
t it? LuaPlus removes
this entirely and wraps the whole thing in a single C++ class called
LuaState
.
To create a
LuaState
object, call the static
Create()
function. Call
Destroy()
to
destroy it. Do not use
new
or
delete
on these objects.
// All LuaPlus objects are under this namespace. I will omit it from future
// code listings.
using namespace LuaPlus;
// This is called during the initialization of your application.
LuaState* pLuaState = LuaState::Create();
// This is done during the destruction of your application.
LuaState::Destroy(pLuaState);
pLuaState = NULL;
LuaState
has a number of very useful functions for accessing the Lua execution
unit as a whole. Two key functions are
DoString()
and
DoFile()
, both of which
take a string as an argument.
DoString()
will parse and execute an arbitrary string
as Lua code.
DoFile()
will open, parse, and execute a file.
pLuaState->DoFile(
“
test.lua
”
); // execute the test.lua file
pLuaState->DoString(
“
x={}
”
);
// after this line, there will be a new global
// variable called x, which is an empty table.
The
LuaObject
class represents a single Lua variable. This can be a number, string,
table, function,
nil
, or any other object Lua supports. This is the main interface for
dealing with Lua variables. Note that a
LuaObject
is considered a strong reference