aboutsummaryrefslogtreecommitdiffstats
path: root/lib/sol2/examples/source/functions_empty_arguments.cpp
diff options
context:
space:
mode:
authorAndy <drumsetmonkey@gmail.com>2019-08-29 13:07:45 -0400
committerAndy <drumsetmonkey@gmail.com>2019-08-29 13:07:45 -0400
commit4ac4b280abf2ffa28caa5a532353115a3033444f (patch)
tree2a13d658bb454360b2faf401244bb0321d3460d4 /lib/sol2/examples/source/functions_empty_arguments.cpp
parente9758416b18b27a65337c28d9641afc0ee89b34b (diff)
parent7a46fa2dd3dad3f038bf8e7339bc67abca428ae6 (diff)
Started creating scripting library/namespace and added sol2 for interfacing
Diffstat (limited to 'lib/sol2/examples/source/functions_empty_arguments.cpp')
-rw-r--r--lib/sol2/examples/source/functions_empty_arguments.cpp53
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/sol2/examples/source/functions_empty_arguments.cpp b/lib/sol2/examples/source/functions_empty_arguments.cpp
new file mode 100644
index 0000000..6d93e9b
--- /dev/null
+++ b/lib/sol2/examples/source/functions_empty_arguments.cpp
@@ -0,0 +1,53 @@
+#define SOL_ALL_SAFETIES_ON 1
+#include <sol/sol.hpp>
+
+#include "assert.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;
+} \ No newline at end of file