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
111
112
113
114
115
116
117
118
119
120
121
|
#include "LuaBindInternal.h"
#include "LuaBindVM.h"
namespace LuaBind
{
static cc8* kStrongTableName = "GAMELAB_UNIVERSAL_STRONG_REFERENCE_TABLE";
static cc8* kWeakTableName = "GAMELAB_UNIVERSAL_WEAK_REFERENCE_TABLE";
std::map<global_State*, VM*> VM::VMs; // 通过线程查找虚拟机,为了方便
VM* VM::TryGetVM(global_State* gState)
{
auto it = VMs.find(gState);
if (it != VMs.end())
return it->second;
else
return NULL;
}
VM* VM::TryGetVM(lua_State* state)
{
return TryGetVM(G(state));
}
VM::VM()
: mStrongRefTable(this)
, mWeakRefTable(this)
, mClasses()
{
mMainThread = luaL_newstate();
mGlobalState = G(mMainThread);
VMs.insert(std::pair<global_State*, VM*>(mGlobalState, this));
}
VM::~VM()
{
VMs.erase(mGlobalState);
lua_close(mMainThread);
}
// 初始化context
void VM::Setup()
{
LUA_BIND_STATE(mMainThread);
mStrongRefTable.Init(kStrongTableName);
mWeakRefTable.Init(kWeakTableName, "v");
}
lua_State* VM::CreateThread()
{
lua_State* thread = lua_newthread(mMainThread);
assert(thread);
return thread;
}
lua_State* VM::GetMainThread()
{
return mMainThread;
}
void VM::SetCurThread(lua_State* cur)
{
if (this)
{
mCurThread = cur;
}
}
lua_State* VM::GetCurThread()
{
return mCurThread;
}
State VM::GetMainState()
{
return mMainThread;
}
RefTable& VM::GetStrongRefTable()
{
return mStrongRefTable;
}
RefTable& VM::GetWeakRefTable()
{
return mWeakRefTable;
}
void VM::OpenLibs()
{
assert(mMainThread);
luaL_openlibs(mMainThread);
}
int VM::RegisterNativeClass(State& state, int classID, int index)
{
assert(state.GetVM() == this);
assert(mClasses.count(classID) == 0);
StrongRef ref = StrongRef(this);
ref.SetRef(state, index);
auto cls = std::pair<int, StrongRef>(classID, ref);
mClasses.insert(cls);
return 1;
}
void VM::PushClassTable(State& state, int classID)
{
assert(state.GetVM() == this);
auto ref = mClasses.find(classID);
if (ref == mClasses.end())
{
state.PushNil();
return;
}
StrongRef cls = ref->second;
cls.PushRef(state);
}
}
|