2017-04-03 04:10:00 +08:00
|
|
|
#define SOL_CHECK_ARGUMENTS
|
2016-08-11 08:39:30 +08:00
|
|
|
#include <sol.hpp>
|
|
|
|
|
|
|
|
#include <iostream>
|
2016-08-23 10:45:06 +08:00
|
|
|
#include <cassert>
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
// Uses some of the fancier bits of sol2, including the "transparent argument",
|
|
|
|
// sol::this_state, which gets the current state and does not increment
|
|
|
|
// function arguments
|
|
|
|
sol::object fancy_func(sol::object a, sol::object b, sol::this_state s) {
|
|
|
|
sol::state_view lua(s);
|
|
|
|
if (a.is<int>() && b.is<int>()) {
|
2016-08-11 21:34:03 +08:00
|
|
|
return sol::object(lua, sol::in_place, a.as<int>() + b.as<int>());
|
2016-08-11 08:39:30 +08:00
|
|
|
}
|
|
|
|
else if (a.is<bool>()) {
|
|
|
|
bool do_triple = a.as<bool>();
|
2016-08-11 21:34:03 +08:00
|
|
|
return sol::object(lua, sol::in_place<double>, b.as<double>() * (do_triple ? 3 : 1));
|
2016-08-11 08:39:30 +08:00
|
|
|
}
|
2016-08-11 21:34:03 +08:00
|
|
|
// Can also use make_object
|
2016-08-11 08:39:30 +08:00
|
|
|
return sol::make_object(lua, sol::nil);
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
sol::state lua;
|
|
|
|
|
|
|
|
lua["f"] = fancy_func;
|
|
|
|
|
|
|
|
int result = lua["f"](1, 2);
|
|
|
|
// result == 3
|
2016-08-23 10:45:06 +08:00
|
|
|
assert(result == 3);
|
2016-08-11 08:39:30 +08:00
|
|
|
double result2 = lua["f"](false, 2.5);
|
|
|
|
// result2 == 2.5
|
2016-08-23 10:45:06 +08:00
|
|
|
assert(result2 == 2.5);
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
// call in Lua, get result
|
|
|
|
// notice we only need 2 arguments here, not 3 (sol::this_state is transparent)
|
|
|
|
lua.script("result3 = f(true, 5.5)");
|
|
|
|
double result3 = lua["result3"];
|
|
|
|
// result3 == 16.5
|
2016-08-23 10:45:06 +08:00
|
|
|
assert(result3 == 16.5);
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
std::cout << "=== any_return example ===" << std::endl;
|
|
|
|
std::cout << "result : " << result << std::endl;
|
|
|
|
std::cout << "result2: " << result2 << std::endl;
|
|
|
|
std::cout << "result3: " << result3 << std::endl;
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|