usertypes.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include "catch.hpp"
  2. #include <lua.hpp>
  3. #include <luwra.hpp>
  4. #include <memory>
  5. struct A {
  6. int a;
  7. A() {}
  8. };
  9. TEST_CASE("usertypes_local_state") {
  10. lua_State* state = luaL_newstate();
  11. REQUIRE(luwra::internal::user_type_id<A> == (void*) INTPTR_MAX);
  12. luwra::register_user_type<A>(state, {});
  13. REQUIRE(luwra::internal::user_type_id<A> != (void*) INTPTR_MAX);
  14. A* instance = new A;
  15. luwra::Value<A*>::push(state, instance);
  16. REQUIRE(luwra::internal::get_user_type_id(state, -1) == luwra::internal::user_type_id<A>);
  17. REQUIRE(luwra::internal::check_user_type<A>(state, -1) == instance);
  18. lua_close(state);
  19. }
  20. struct B {
  21. int prop;
  22. int increment(int x) {
  23. return prop += x;
  24. }
  25. B* add(const B* other) {
  26. return new B {prop + other->prop};
  27. }
  28. };
  29. TEST_CASE("usertypes_lua_usage") {
  30. lua_State* state = luaL_newstate();
  31. luwra::register_user_type<B>(
  32. state,
  33. {
  34. {"increment", luwra::wrap_method<B, int(int), &B::increment>},
  35. {"prop", luwra::wrap_property<B, int, &B::prop>}
  36. },
  37. {
  38. {"__add", luwra::wrap_method<B, B*(const B*), &B::add>}
  39. }
  40. );
  41. B* value = new B {1337};
  42. luwra::register_global(state, "value", value);
  43. REQUIRE(luaL_dostring(state, "return value:prop()") == 0);
  44. REQUIRE(luwra::Value<int>::read(state, -1) == value->prop);
  45. REQUIRE(luaL_dostring(state, "value:prop(7331)") == 0);
  46. REQUIRE(value->prop == 7331);
  47. REQUIRE(luaL_dostring(state, "value:increment(-7329)") == 0);
  48. REQUIRE(value->prop == 2);
  49. REQUIRE(luaL_dostring(state, "return value + value") == 0);
  50. REQUIRE(luwra::Value<B*>::read(state, -1)->prop == 4);
  51. lua_close(state);
  52. }
  53. TEST_CASE("usertypes_gchook_tref") {
  54. lua_State* state = luaL_newstate();
  55. luwra::register_user_type<std::shared_ptr<int>>(state, {});
  56. std::shared_ptr<int> shared_var = std::make_shared<int>(1337);
  57. REQUIRE(shared_var.use_count() == 1);
  58. luwra::Value<std::shared_ptr<int>&>::push(state, shared_var);
  59. REQUIRE(shared_var.use_count() == 2);
  60. lua_close(state);
  61. REQUIRE(shared_var.use_count() == 1);
  62. }
  63. TEST_CASE("usertypes_gchook_tptr") {
  64. lua_State* state = luaL_newstate();
  65. luwra::register_user_type<std::shared_ptr<int>>(state, {});
  66. std::shared_ptr<int> shared_var = std::make_shared<int>(1337);
  67. REQUIRE(shared_var.use_count() == 1);
  68. luwra::Value<std::shared_ptr<int>*>::push(state, &shared_var);
  69. REQUIRE(shared_var.use_count() == 1);
  70. lua_close(state);
  71. REQUIRE(shared_var.use_count() == 1);
  72. }