Game Development Reference
In-Depth Information
In Lua, tables are used for just about everything. A variable is really just a field in a
table indexed by a string. That string is the variable name. When you define a global
variable in Lua, what really happens is that Lua inserts it into a special table where all
global variables live. There
'
s nothing special about this table; you can even access it
directly.
-- These two lines are equivalent
x=10
_G[
“
x
”
]=10
-- This will print out all global variables
for key, val in pairs(_G) do
print(key, val)
end
In fact, if you
re feeling really crazy, you can even change the behavior of global vari-
ables by assigning a metatable to
_G
with
__index
or
__newindex
defined! You
could completely forbid new global variables or call a function whenever a global is
accessed or set.
'
Don
'
t Do That
Just because you can modify the behavior of the globals table doesn
t mean
you should. Leave it alone unless you have a really, really,
really
good
reason. I
'
ve shipped five professional games with Lua, and we never once
had to mess with the behavior of this table. Chances are, neither will you.
'
To access a global variable in LuaPlus, you grab the globals table from the
LuaState
object and access it like any other member. Here
'
s the missing code from the exam-
ple above that gets the
positionVec
global:
LuaObject globals = pLuaState->GetGlobals();
LuaObject positionTable = globals.GetByName(
“
positionVec
”
);
Once you have this globals table, you can assign values as well:
globals.SetString(
);
This creates a global variable called
programName
and sets it to the value of
“Teapot Wars.”
“
programName
”
,
“
Teapot Wars
”
You can access it in Lua as normal:
print(programName) -- > prints
“
Teapot Wars
”