summaryrefslogtreecommitdiff
path: root/Runtime/LuaBind/LuaBindVM.cpp
blob: 268a5ed1cc1507b7088be7fd88ca9db5f5c339e7 (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
#include "LuaBindInternal.h"
#include "LuaBindVM.h"

namespace LuaBind
{

	VM::VMap VM::VMs;   // 通过线程查找虚拟机,为了方便

	VM* VM::TryGetVM(global_State* gState)
	{
		auto it = VMs.find(gState);
		if (it != VMs.end())
			return it->second;
		else
			return nullptr;
	}

	VM* VM::TryGetVM(lua_State* state)
	{
		return TryGetVM(G(state));
	}

	VM::VM()
		: mStrongRefTable()
		, mWeakRefTable()
	{
		mMainThread = luaL_newstate();
		assert(mMainThread);
		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(state, "GAMELAB_UNIVERSAL_STRONG_REFERENCE_TABLE");
		mWeakRefTable.Init(state, "GAMELAB_UNIVERSAL_WEAK_REFERENCE_TABLE", "v");
	}

	lua_State* VM::CreateThread()
	{
		lua_State* thread = lua_newthread(mMainThread);
		assert(thread);
		return thread;
	}

	lua_State* VM::GetMainThread()
	{
		return mMainThread;
	}

	State VM::GetMainState()
	{
		return mMainThread;
	}

	RefTable& VM::GetStrongRefTable()
	{
		return mStrongRefTable;
	}

	RefTable& VM::GetWeakRefTable()
	{
		return mWeakRefTable;
	}

	void VM::OpenLibs()
	{
		assert(mMainThread);
		luaL_openlibs(mMainThread);
	}

}