MCPcopy Create free account
hub / github.com/ThePhD/sol2 / main

Function main

examples/source/functions_empty_arguments.cpp:6–54  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main(int, char*[]) {
7 std::cout << "=== functions empty args ===" << std::endl;
8
9 // sol::reference, sol::Stack_reference,
10 // sol::object (and main_* types) can all be
11 // used to capture "nil", or "none" when a function
12 // leaves it off
13 auto my_defaulting_function
14 = [](sol::object maybe_defaulted) -> int {
15 // if it's nil, it's "unused" or "inactive"
16 bool inactive = maybe_defaulted == sol::lua_nil;
17 if (inactive) {
18 return 0;
19 }
20 if (maybe_defaulted.is<int>()) {
21 int value = maybe_defaulted.as<int>();
22 return value;
23 }
24 return 1;
25 };
26
27 sol::state lua;
28 lua.open_libraries(sol::lib::base);
29
30 // copy function in (use std::ref to change this behavior)
31 lua.set_function(
32 "defaulting_function", my_defaulting_function);
33
34 sol::string_view code = R"(
35 result = defaulting_function(24)
36 result_nothing = defaulting_function()
37 result_nil = defaulting_function(nil)
38 result_string = defaulting_function('meow')
39 print('defaulting_function(24), returned:', result)
40 print('defaulting_function(), returned:', result_nothing)
41 print('defaulting_function(nil), returned:', result_nil)
42 print('defaulting_function(\'meow\'), returned:', result_string)
43 assert(result == 24)
44 assert(result_nothing == 0)
45 assert(result_nil == 0)
46 assert(result_string == 1)
47 )";
48
49 lua.safe_script(code);
50
51 std::cout << std::endl;
52
53 return 0;
54}

Callers

nothing calls this directly

Calls 2

open_librariesMethod · 0.80
safe_scriptMethod · 0.80

Tested by

no test coverage detected