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

Function main

examples/source/variadic_args_into_lua.cpp:6–53  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main() {
7 std::cout << "=== variadic_args ===" << std::endl;
8
9 sol::state lua;
10 lua.open_libraries(sol::lib::base);
11
12 // another function, which doubles the argument
13 lua.script("function doubler (x) return x * 2 end");
14 sol::protected_function doubler = lua["doubler"];
15
16 // Function requires 2 arguments
17 // rest can be variadic, but:
18 // va will include everything after "a" argument,
19 // which means "b" will be part of the varaidic_args list
20 // too at position 0
21 lua.set_function("v",
22 [doubler](int a, sol::variadic_args va, int /*b*/) {
23 int r = 0;
24 for (auto v : va) {
25 int value = doubler(
26 v); // pass directly to Lua as well!
27 r += value;
28 }
29 // Only have to add a, b was included from
30 // variadic_args and beyond use explicit "call"
31 // syntax to return exactly an integer! this is
32 // useful for ambiguous operator overloads in C++
33 // and other shenanigans
34 return r + a;
35 });
36
37 lua.script("x = v(25, 25)");
38 lua.script("x2 = v(25, 25, 100, 50, 250, 150)");
39 lua.script("x3 = v(1, 2, 3, 4, 5, 6)");
40 // will error: not enough arguments!
41 // lua.script("x4 = v(1)");
42
43 lua.script("assert(x == 75)");
44 lua.script("assert(x2 == 1175)");
45 lua.script("assert(x3 == 41)");
46 lua.script("print(x)");
47 lua.script("print(x2)");
48 lua.script("print(x3)");
49
50 std::cout << std::endl;
51
52 return 0;
53}

Callers

nothing calls this directly

Calls 2

open_librariesMethod · 0.80
scriptMethod · 0.80

Tested by

no test coverage detected