Game Development Reference
In-Depth Information
Memory Management
Like most scripting languages, Lua uses automatic memory management and garbage
collection. This works very much like TR1
s shared_ptr construct. Every variable
you create is reference counted, and when all references go away, the object is
marked for garbage collection. Lua periodically runs a garbage collection cycle
where it walks through the garbage list and frees up memory. You don
'
'
t have to do
this manually; it
s done automatically by Lua. If you do want to force a garbage col-
lection cycle, you can call the collectgarbage() function.
'
Global Variables Are Here to Stay
Global variables are never garbage collected until the program shuts down.
They can be accessed by any part of the program at any time, so Lua has no
way of knowing when you don
'
t need them anymore. When you
'
re done with a
global variable, it
s good to assign nil to it. Assuming there are no other
references, this will cause Lua to mark it as collectable.
'
Binding Lua to C++
Hopefully by now you have a pretty good understanding of Lua and how it works.
The remainder of this chapter will build upon this foundation and create a working
relationship between Lua script and the C++ engine we
'
ve been creating throughout
this entire book. First, we
ll look at some integration strategies and third-party librar-
ies to make the process of embedding Lua into the C++ engine easier. Then we
'
ll go
over some of the glue to get Lua to play nicely with the Process Manager and event
system. Finally, I ' ll bring it all together with a couple of examples.
'
The Lua C API
As I said earlier in this chapter, Lua was built from the ground up to be integrated
into an existing system. (Its original intent was to be an embedded configuration
language.) To facilitate this, there is a core C API for integrating Lua into your code-
base. Unfortunately, this API is rather lacking in terms of usability. You have to
manually deal with the Lua stack and language internals. Binding C functions to the
Lua API is not particularly easy, and calling Lua functions from C is equally difficult.
Good luck trying to bind a C++ class or function!
With a bit of work, you can get the Lua C API to function in your programs, but it
s
certainly not ideal. There are a large number of binding libraries that make this job a
lot easier. They are typically built on top of the core C API, although that
'
'
s not
always the case.
 
 
 
 
Search WWH ::




Custom Search