2019-05-21 19:17:31 -04:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-27 22:27:38 -07:00
|
|
|
#include <sol/sol.hpp>
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
2021-03-06 10:14:48 -05: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) {
|
2016-08-10 20:39:30 -04:00
|
|
|
sol::state_view lua(s);
|
|
|
|
|
if (a.is<int>() && b.is<int>()) {
|
2021-03-06 10:14:48 -05:00
|
|
|
return sol::object(
|
|
|
|
|
lua, sol::in_place, a.as<int>() + b.as<int>());
|
2016-08-10 20:39:30 -04:00
|
|
|
}
|
|
|
|
|
else if (a.is<bool>()) {
|
|
|
|
|
bool do_triple = a.as<bool>();
|
2021-03-06 10:14:48 -05:00
|
|
|
return sol::object(lua,
|
|
|
|
|
sol::in_place_type<double>,
|
|
|
|
|
b.as<double>() * (do_triple ? 3 : 1));
|
2016-08-10 20:39:30 -04:00
|
|
|
}
|
2016-08-11 09:34:03 -04:00
|
|
|
// Can also use make_object
|
2019-05-26 13:32:28 -04:00
|
|
|
return sol::make_object(lua, sol::lua_nil);
|
2016-08-10 20:39:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
|
sol::state lua;
|
|
|
|
|
|
|
|
|
|
lua["f"] = fancy_func;
|
|
|
|
|
|
|
|
|
|
int result = lua["f"](1, 2);
|
|
|
|
|
// result == 3
|
2022-09-28 01:56:26 -04:00
|
|
|
SOL_ASSERT(result == 3);
|
2016-08-10 20:39:30 -04:00
|
|
|
double result2 = lua["f"](false, 2.5);
|
|
|
|
|
// result2 == 2.5
|
2022-09-28 01:56:26 -04:00
|
|
|
SOL_ASSERT(result2 == 2.5);
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
|
// call in Lua, get result
|
2021-03-06 10:14:48 -05:00
|
|
|
// notice we only need 2 arguments here, not 3
|
|
|
|
|
// (sol::this_state is transparent)
|
2016-08-10 20:39:30 -04:00
|
|
|
lua.script("result3 = f(true, 5.5)");
|
|
|
|
|
double result3 = lua["result3"];
|
|
|
|
|
// result3 == 16.5
|
2022-09-28 01:56:26 -04:00
|
|
|
SOL_ASSERT(result3 == 16.5);
|
2021-03-06 01:03:23 -05:00
|
|
|
|
2018-03-15 17:16:28 -04:00
|
|
|
std::cout << "=== any_return ===" << std::endl;
|
2016-08-10 20:39:30 -04:00
|
|
|
std::cout << "result : " << result << std::endl;
|
|
|
|
|
std::cout << "result2: " << result2 << std::endl;
|
|
|
|
|
std::cout << "result3: " << result3 << std::endl;
|
|
|
|
|
std::cout << std::endl;
|
2019-03-09 20:57:49 -05:00
|
|
|
|
|
|
|
|
return 0;
|
2022-09-28 01:56:26 -04:00
|
|
|
}
|