nngn
Loading...
Searching...
No Matches
function.h File Reference

Operations on callable types, function call implementation. More...

#include <optional>
#include <tuple>
#include <utility>
#include <lua.hpp>
#include "utils/log.h"
#include "lua.h"
#include "push.h"
#include "state.h"
#include "utils.h"
#include "value.h"
Include dependency graph for function.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  nngn::lua::detail::function_base< CRTP >
 Reference to a function on the stack. More...
 
struct  nngn::lua::function_view
 Non-owning reference to a function on the stack. More...
 
struct  nngn::lua::function_value
 Owning reference to a function on the stack. More...
 

Namespaces

namespace  nngn
 
namespace  nngn::lua
 
namespace  nngn::lua::detail
 

Functions

template<typename R , typename ... Args>
nngn::lua::call (lua_State *L, R(*f)(Args...), int i)
 Calls the regular function f with arguments taken from the stack.
 
template<typename R , typename T , typename ... Args>
nngn::lua::call (lua_State *L, R(T::*f)(Args...), int i)
 Calls member function f with object/arguments taken from the stack.
 
template<stateless_lambda T>
 nngn::lua::call (lua_State *L, T, int i)
 Calls a stateless lambda.
 

Detailed Description

Operations on callable types, function call implementation.

The main object which implements Lua function calls is function_base. Its operator() pushes all arguments onto the stack and performs a lua_(p)call (depending on debug/release settings). function_view and function_value are the equivalent of value_view and value with the function_base mixin.

An alternative group of functions is call, which can be thought of as the reverse of function_base: they are used to call C/++ functions and take arguments and return values from/to Lua stack. All arguments are assumed to be already on the stack; return values are pushed after the execution of the function. Because the types of arguments and return values are inferred from the function (pointer) argument to call, it must be a resolved value: an overloaded function must be cast, a function template must be explicitly instantiated, etc.

Examples

Calling a Lua function:

lua.dostring("function f(i) return i + 1 end");
function_value{lua.globals()["f"]}(42);
assert(lua.get(-1) == 43);
assert
Definition: debug.lua:3

Pushing a C/++ function and calling it:

constexpr auto f = [](state_view l) {
l.globals()["g"] = true;
return 42;
};
function_value{lua.push(f)}();
assert(lua.get(-1) == 42);
assert(lua.globals()["g"] == true);
function g l
Definition: plot.lua:8
function f()) end

The same, but set and called through Lua:

lua.globals()["f"] = f;
function_value{lua.globals()["f"]}();
// …

Calling a C/++ function using stack values and pushing the result:

lua.push(42);
lua.push(43.0);
lua.push(call(lua, [](int i, float f) {
return static_cast<float>(i) + f;
}));
assert(lua.get(-1) == 85.0);