aboutsummaryrefslogtreecommitdiffstats
path: root/lib/LuaBridge/Tests/Source/RefCountedPtrTests.cpp
blob: 4e5f58290109a4a6c2bbe68ef202b3b017205647 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// https://github.com/vinniefalco/LuaBridge
//
// Copyright 2019, Dmitry Tarakanov
// SPDX-License-Identifier: MIT

#include "TestBase.h"

#include "LuaBridge/RefCountedPtr.h"


struct RefCountedPtrTests : TestBase
{
  template <class T>
  T variable(const std::string& name)
  {
    runLua("result = " + name);
    return result().cast <T>();
  }
};

namespace {

struct RefCounted : luabridge::RefCountedObject
{
  explicit RefCounted(bool& deleted)
    : deleted (deleted)
  {
    deleted = false;
  }

  ~RefCounted()
  {
    deleted = true;
  }

  bool isDeleted () const
  {
    return deleted;
  }

  bool& deleted;
};

} // namespace

TEST_F (RefCountedPtrTests, Operators)
{
  bool deleted1 = false;
  auto* raw_ptr1 = new RefCounted (deleted1);
  luabridge::RefCountedObjectPtr <RefCounted> ptr1 (raw_ptr1);

  bool deleted2 = false;
  auto* raw_ptr2 = new RefCounted (deleted2);
  luabridge::RefCountedObjectPtr <RefCounted> ptr2 (raw_ptr2);

  ASSERT_TRUE (raw_ptr1 == ptr1.getObject ());
  ASSERT_TRUE (ptr1.getObject () == raw_ptr1);
}

TEST_F (RefCountedPtrTests, LastReferenceInLua)
{
  luabridge::getGlobalNamespace (L)
    .beginClass <RefCounted> ("Class")
    .addProperty ("deleted", &RefCounted::isDeleted)
    .endClass ();

  bool deleted = false;

  luabridge::RefCountedObjectPtr <RefCounted> object (new RefCounted (deleted));

  luabridge::setGlobal (L, object, "object");
  runLua("result = object.deleted");
  ASSERT_EQ (true, result ().isBool ());
  ASSERT_EQ (false, result <bool> ());

  object = nullptr;
  runLua("result = object.deleted");
  ASSERT_EQ(true, result ().isBool ());
  ASSERT_EQ(false, result <bool>());
  ASSERT_EQ(false, deleted);

  runLua ("object = nil");
  lua_gc (L, LUA_GCCOLLECT, 1);

  ASSERT_EQ (true, deleted);
}

TEST_F (RefCountedPtrTests, LastReferenceInCpp)
{
  luabridge::getGlobalNamespace (L)
    .beginClass <RefCounted> ("Class")
    .addProperty ("deleted", &RefCounted::isDeleted)
    .endClass ();

  bool deleted = false;

  luabridge::RefCountedObjectPtr <RefCounted> object (new RefCounted (deleted));

  luabridge::setGlobal (L, object, "object");
  runLua("result = object.deleted");
  ASSERT_EQ (true, result ().isBool ());
  ASSERT_EQ (false, result <bool> ());

  runLua ("object = nil");
  lua_gc (L, LUA_GCCOLLECT, 1);
  ASSERT_EQ(false, deleted);

  object = nullptr;
  ASSERT_EQ (true, deleted);
}