aboutsummaryrefslogtreecommitdiffstats
path: root/lib/sol2/examples/source/customization_convert_on_get.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/customization_convert_on_get.cpp
parente9758416b18b27a65337c28d9641afc0ee89b34b (diff)
parent7a46fa2dd3dad3f038bf8e7339bc67abca428ae6 (diff)
Started creating scripting library/namespace and added sol2 for interfacing
Diffstat (limited to 'lib/sol2/examples/source/customization_convert_on_get.cpp')
-rw-r--r--lib/sol2/examples/source/customization_convert_on_get.cpp54
1 files changed, 54 insertions, 0 deletions
diff --git a/lib/sol2/examples/source/customization_convert_on_get.cpp b/lib/sol2/examples/source/customization_convert_on_get.cpp
new file mode 100644
index 0000000..da2b5da
--- /dev/null
+++ b/lib/sol2/examples/source/customization_convert_on_get.cpp
@@ -0,0 +1,54 @@
+#define SOL_ALL_SAFETIES_ON 1
+#include <sol/sol.hpp>
+
+#include <iostream>
+#include <iomanip>
+#include "assert.hpp"
+
+struct number_shim {
+ double num = 0;
+};
+
+template <typename Handler>
+bool sol_lua_check(sol::types<number_shim>, lua_State* L, int index, Handler&& handler, sol::stack::record& tracking) {
+ // check_usertype is a backdoor for directly checking sol3 usertypes
+ if (!sol::stack::check_usertype<number_shim>(L, index)
+ && !sol::stack::check<double>(L, index)) {
+ handler(L, index, sol::type_of(L, index), sol::type::userdata, "expected a number_shim or a number");
+ return false;
+ }
+ tracking.use(1);
+ return true;
+}
+
+number_shim sol_lua_get(sol::types<number_shim>, lua_State* L, int index, sol::stack::record& tracking) {
+ if (sol::stack::check_usertype<number_shim>(L, index)) {
+ number_shim& ns = sol::stack::get_usertype<number_shim>(L, index, tracking);
+ return ns;
+ }
+ number_shim ns{};
+ ns.num = sol::stack::get<double>(L, index, tracking);
+ return ns;
+}
+
+int main() {
+ sol::state lua;
+
+ // Create a pass-through style of function
+ lua.safe_script("function f ( a ) return a end");
+ lua.set_function("g", [](double a) {
+ number_shim ns;
+ ns.num = a;
+ return ns;
+ });
+
+ lua.script("vf = f(25) vg = g(35)");
+
+ number_shim thingsf = lua["vf"];
+ number_shim thingsg = lua["vg"];
+
+ c_assert(thingsf.num == 25);
+ c_assert(thingsg.num == 35);
+
+ return 0;
+}