as_function

make sure an object is pushed as a function

template <typename Sig = sol::function_sig<>, typename... Args>
function_argumants<Sig, Args...> as_function ( Args&& ... );

This function serves the purpose of ensuring that a callable struct (like a lambda) can be passed to the set( key, value ) calls on sol::table and be treated like a function binding instead of a userdata. It is recommended that one uses the sol::table::set_function call instead, but if for some reason one must use set, then as_function can help ensure a callable struct is handled like a lambda / callable, and not as just a userdata structure.

This class can also make it so usertypes bind variable types as functions to for usertype bindings.

 1#define SOL_ALL_SAFETIES_ON 1
 2#include <sol/sol.hpp>
 3
 4int main() {
 5	struct callable {
 6		int operator()(int a, bool b) {
 7			return a + (b ? 10 : 20);
 8		}
 9	};
10
11
12	sol::state lua;
13	// Binds struct as userdata
14	// can still be callable, but beware
15	// caveats
16	lua.set("not_func", callable());
17	// Binds struct as function
18	lua.set("func", sol::as_function(callable()));
19	// equivalent: lua.set_function( "func", callable() );
20	// equivalent: lua["func"] = callable();
21}

Note that if you actually want a userdata, but you want it to be callable, you simply need to create a sol::table::new_usertype and then bind the "__call" metamethod (or just use sol::meta_function::call enumeration). This may or may not be done automatically for you, depending on whether or not the call operator is overloaded and such.

Here’s an example of binding a variable as a function to a usertype:

 1#define SOL_ALL_SAFETIES_ON 1
 2#include <sol/sol.hpp>
 3
 4int main() {
 5	class B {
 6	public:
 7		int bvar = 24;
 8	};
 9
10	sol::state lua;
11	lua.open_libraries(sol::lib::base);
12	lua.new_usertype<B>("B",
13	     // bind as variable
14	     "b",
15	     &B::bvar,
16	     // bind as function
17	     "f",
18	     sol::as_function(&B::bvar));
19
20	B b;
21	lua.set("b", &b);
22	lua.script(R"(x = b:f()
23		y = b.b
24		assert(x == 24)
25		assert(y == 24)
26	)");
27
28	return 0;
29}