Lua-API++  2015-02-12-3
Lua-API++ library
Automatic stack management

The library aims to free you of tedious stack management completely. You can freely use indexing, function calls, arithmetics, concatenation and so on, with nesting operation results and never worry about placing temporary values on the stack in correct order or removing those you no longer need. It is done by Lua API++ objects.

These objects allow smooth operations when used correctly. There are some limitations on how these objects can be used without breaking the stack integrity. These objects are responsible for allocating and freeing space on Lua stack. In order to do so, these objects must have strictly controlled lifetime (only be declared as local variables), must not be copied, moved (with some safe exceptions like creating a value anchor by assignment), stored in containers or be inherited from. Many unsafe operations are already disabled for those objects, but there are still some ways left to break their proper functioning.

In short, it is useful to remember this:

  • State cannot be copied or moved.
  • Context is given to function, it cannot be copied, moved, stored or created (exception: Context can be created explicitly if necessary).
  • Retvals can only be created by calling ret in return statement. They cannot be copied or moved, but can be returned from functions.
  • Non-owning value references may be freely copied and passed around, but their lifetime must never extend the lifetime of anchor objects they refer to.
  • Value anchors are designed to be used as local variables only, to preserve correct push/pop order. They may be passed to and returned from functions, but only in one direction.
  • Temporaries that are created as result of operation are designed to be used as temporaries only. If you want to capture their value, anchor it, because auto won't work.
Note
The possibility to return Retvals and anchor objects from functions is built around compiler feature named RVO. You may get link errors if your compiler doesn't support it, or it was disabled, or failed to work properly.

Passing values to and returning from functions

It is possible to pass into functions and return anchor objects and value references, but not as freely as normal values:

References

Returned value references must reference only anchor objects existing outside of called function.

Anchors

Function may have anchor object as return type or in parameters, but not both. You may easily memorize this rule as "one-way rule" or "in or out rule". While both of these actions make sense and are useful, doing them simultaneously will break the stack and cause incorrect behavior, so it's usability over safety choice. A good reason to have anchors as parameters or return type is their ability to capture the contents of temporaries (so a temporary-producing expression may be passed into function or returned from it).