2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
int main() {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== variadic_args ===" << std::endl;
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
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,
|
2021-03-06 23:14:48 +08:00
|
|
|
// 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;
|
|
|
|
});
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
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)");
|
2020-03-31 12:22:46 +08:00
|
|
|
// will error: not enough arguments!
|
|
|
|
// lua.script("x4 = v(1)");
|
2016-08-11 08:39:30 +08:00
|
|
|
|
2017-12-26 21:04:54 +08:00
|
|
|
lua.script("assert(x == 50)");
|
|
|
|
lua.script("assert(x2 == 600)");
|
|
|
|
lua.script("assert(x3 == 21)");
|
2020-03-31 12:22:46 +08:00
|
|
|
lua.script("print(x)"); // 50
|
2016-08-11 08:39:30 +08:00
|
|
|
lua.script("print(x2)"); // 600
|
|
|
|
lua.script("print(x3)"); // 21
|
2018-03-17 04:47:09 +08:00
|
|
|
|
2016-08-11 08:39:30 +08:00
|
|
|
std::cout << std::endl;
|
2018-03-17 04:47:09 +08:00
|
|
|
|
|
|
|
return 0;
|
2016-08-11 08:39:30 +08:00
|
|
|
}
|