A RAII model for values on the Lua stack. More...
#include <stack_cleaner.hpp>
Classes | |
struct | impl |
Internal implementation for lutok::stack_cleaner. More... |
Public Member Functions | |
stack_cleaner (state &) | |
Creates a new stack cleaner. | |
~stack_cleaner (void) | |
Pops any values from the stack not known at construction time. | |
void | forget (void) |
Forgets about any elements currently in the stack. |
Private Member Functions | |
stack_cleaner (const stack_cleaner &) | |
Disallow copies. | |
stack_cleaner & | operator= (const stack_cleaner &) |
Disallow assignment. |
Private Attributes | |
std::auto_ptr< impl > | _pimpl |
Pointer to the shared internal implementation. |
A RAII model for values on the Lua stack.
At creation time, the object records the current depth of the Lua stack and, during destruction, restores the recorded depth by popping as many stack entries as required. As a corollary, the stack can only grow during the lifetime of a stack_cleaner object (or shrink, but cannot become shorter than the depth recorded at creation time).
Use this class as follows:
state s; { stack_cleaner cleaner1(s); s.push_integer(3); s.push_integer(5); ... do stuff here ... for (...) { stack_cleaner cleaner2(s); s.load_string("..."); s.pcall(0, 1, 0); ... do stuff here ... } // cleaner2 destroyed; the result of pcall is gone. } // cleaner1 destroyed; the integers 3 and 5 are gone.
You must give a name to the instantiated objects even if they cannot be accessed later. Otherwise, the instance will be destroyed right away and will not have the desired effect.
lutok::stack_cleaner::stack_cleaner | ( | state & | state_ | ) |
Creates a new stack cleaner.
This gathers the current height of the stack so that extra elements can be popped during destruction.
state_ | The Lua state. |
lutok::stack_cleaner::~stack_cleaner | ( | void | ) |
Pops any values from the stack not known at construction time.
void lutok::stack_cleaner::forget | ( | void | ) |
Forgets about any elements currently in the stack.
This allows a function to return values on the stack because all the elements that are currently in the stack will not be touched during destruction when the function is called.