File: functions_empty_arguments.cpp

package info (click to toggle)
sol2 3.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 23,096 kB
  • sloc: cpp: 43,816; ansic: 1,018; python: 356; sh: 288; makefile: 202
file content (54 lines) | stat: -rw-r--r-- 1,494 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main(int, char*[]) {
	std::cout << "=== functions empty args ===" << std::endl;

	// sol::reference, sol::Stack_reference,
	// sol::object (and main_* types) can all be
	// used to capture "nil", or "none" when a function
	// leaves it off
	auto my_defaulting_function
	     = [](sol::object maybe_defaulted) -> int {
		// if it's nil, it's "unused" or "inactive"
		bool inactive = maybe_defaulted == sol::lua_nil;
		if (inactive) {
			return 0;
		}
		if (maybe_defaulted.is<int>()) {
			int value = maybe_defaulted.as<int>();
			return value;
		}
		return 1;
	};

	sol::state lua;
	lua.open_libraries(sol::lib::base);

	// copy function in (use std::ref to change this behavior)
	lua.set_function(
	     "defaulting_function", my_defaulting_function);

	sol::string_view code = R"(
		result = defaulting_function(24)
		result_nothing = defaulting_function()
		result_nil = defaulting_function(nil)
		result_string = defaulting_function('meow')
		print('defaulting_function(24), returned:', result)
		print('defaulting_function(), returned:', result_nothing)
		print('defaulting_function(nil), returned:', result_nil)
		print('defaulting_function(\'meow\'), returned:', result_string)
		assert(result == 24)
		assert(result_nothing == 0)
		assert(result_nil == 0)
		assert(result_string == 1)
	)";

	lua.safe_script(code);

	std::cout << std::endl;

	return 0;
}