advanced-stack-interaction.md 1.8 KB

Advanced stack interaction

Instead of extracting every Lua value seperately and pushing the result of your C++ function back onto the stack again, you can use one of the following functions to make this process easier for you.

Manual stack layout

The function direct lets you specify a stack signature in order to extract the values and invoke a Callable with them.

Without returning to Lua

Consider the following:

string result = foo(luwra::read<string>(lua, n), luwra::read<int>(lua, n + 1));

It could be rewritting like this:

string result = luwra::direct<string(string, int)>(lua, n, foo);

This will read all the required values off the stack, invoke foo with them and return its value to you.

Returning values to the stack

An alternative to direct is map. It does exactly the same, with the exception that it returns the resulting value back to the Lua stack.

luwra::map<string(string, int)>(lua, n, foo);

Automatic stack layout

apply is similiar to direct. It differs from direct because it is able to infer the stack layout from the given Callable.

Provided a function foo which has been declared as used in the example above:

string foo(string bar, int baz);

One would use foo like this:

string result = luwra::apply(lua, n, foo);

It also works with Lambdas, because they are function objects aswell.

string result = luwra::apply(lua, n, [](string a, int b) -> string {
	// Magic
});