aboutsummaryrefslogtreecommitdiffstats
path: root/lib/sol2/examples/source/variadic_args.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/variadic_args.cpp
parente9758416b18b27a65337c28d9641afc0ee89b34b (diff)
parent7a46fa2dd3dad3f038bf8e7339bc67abca428ae6 (diff)
Started creating scripting library/namespace and added sol2 for interfacing
Diffstat (limited to 'lib/sol2/examples/source/variadic_args.cpp')
-rw-r--r--lib/sol2/examples/source/variadic_args.cpp45
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/sol2/examples/source/variadic_args.cpp b/lib/sol2/examples/source/variadic_args.cpp
new file mode 100644
index 0000000..2d9e557
--- /dev/null
+++ b/lib/sol2/examples/source/variadic_args.cpp
@@ -0,0 +1,45 @@
+#define SOL_ALL_SAFETIES_ON 1
+#include <sol/sol.hpp>
+
+#include <iostream>
+
+int main() {
+ std::cout << "=== variadic_args ===" << std::endl;
+
+ sol::state lua;
+ lua.open_libraries(sol::lib::base);
+
+ // Function requires 2 arguments
+ // rest can be variadic, but:
+ // va will include everything after "a" argument,
+ // which means "b" will be part of the varaidic_args list too
+ // at position 0
+ lua.set_function("v", [](int a, sol::variadic_args va, int /*b*/) {
+ int r = 0;
+ for (auto v : va) {
+ int value = v; // get argument out (implicit conversion)
+ // can also do int v = v.as<int>();
+ // can also do int v = va.get<int>(i); with index i
+ r += value;
+ }
+ // Only have to add a, b was included from variadic_args and beyond
+ return r + a;
+ });
+
+ lua.script("x = v(25, 25)");
+ lua.script("x2 = v(25, 25, 100, 50, 250, 150)");
+ lua.script("x3 = v(1, 2, 3, 4, 5, 6)");
+ // will error: not enough arguments
+ //lua.script("x4 = v(1)");
+
+ lua.script("assert(x == 50)");
+ lua.script("assert(x2 == 600)");
+ lua.script("assert(x3 == 21)");
+ lua.script("print(x)"); // 50
+ lua.script("print(x2)"); // 600
+ lua.script("print(x3)"); // 21
+
+ std::cout << std::endl;
+
+ return 0;
+} \ No newline at end of file