aboutsummaryrefslogtreecommitdiff
path: root/src/lua/common/je_lua_shared.hpp
blob: 0a05e1a28f6fc55e5c394f20d8df258de13137c6 (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
#ifndef __JIN_COMMON_SHARED_H__
#define __JIN_COMMON_SHARED_H__

#include <map>
#include <vector>
#include <functional>

struct lua_State;

namespace JinEngine
{
    namespace Lua
    {

        ///
        /// Thread safe.
        ///
        class SharedBase
        {
        public:
            void retain();

            void release();

            void setDependency(int key, SharedBase* shared);

            void removeDependency(int key);

            void removeDependency(SharedBase* dep);

            bool isDependOn(int key);

            bool isDependOn(SharedBase* shared);

            void clearDependencies();

            SharedBase* getDependency(int key);

            bool isType(const char* t);

            int getDependenciesCount();

            const char* getType();

        protected:
            SharedBase(lua_State* L, void* obj, const char* t);

            SharedBase(const SharedBase&);

            virtual ~SharedBase();

            using DepsMap = std::map<int, SharedBase*>;

            lua_State* mL;
            void* mObject;
            int mCount;
            DepsMap mDependencies;
            const char* mType;

        };

        template<class T>
        class Shared : public SharedBase
        {
        public:
            Shared(lua_State* L, T* obj, const char* type)
                : SharedBase(L, obj, type)
            {
            }

            T* operator->()
            {
                return static_cast<T*>(mObject);
            }

            T* getObject()
            {
                return static_cast<T*>(mObject);
            }

        private:
            Shared(const Shared<T>& shared);

            ~Shared()
            {
                T* obj = static_cast<T*>(mObject);
                delete obj;
            }

        };

    } // namespace Lua
} // namespace JinEngine

#endif