Game Development Reference
In-Depth Information
The Lua stack
As Lua is a weakly typed language that supports functions that can receive an arbitrary
amount of parameters as well as return an arbitrary number of return values, interfacing
with C++ code is a bit tricky.
To get around the strong typing of C++, Lua uses a First In First Out ( FIFO ) stack to
send and receive data from the Lua virtual machine. For example, when C++ wants to call
a Lua function, the Lua function as well as the function parameters are pushed onto the
stack and are then executed by the virtual machine. Any return values from the function are
pushed back to the stack for the calling C++ code to handle.
The same process happens in reverse when the Lua code wants to call the C++ code. First,
Lua pushes the C++ function onto the stack, followed by any parameters sent to the func-
tion. Once the code has finished executing, any return values are pushed back to the stack
for the executing Lua script to handle.
The Lua call stack indexing scheme
When interfacing with Lua, stack values can either be retrieved bottom-up, or top-down.
The top element in the stack can be retrieved with an index of -1 , while the bottom ele-
ment of the stack can be retrieved with an index of 1 . Additional elements can be retrieved
by indexing -2 , -3 , 2 , 3 , and so on.
Search WWH ::




Custom Search