summaryrefslogtreecommitdiff
path: root/Runtime/LuaBind/LuaBindEnum.cpp
blob: 63e25678320c783d332bac4f63d45bac406acb15 (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
#include "LuaBindEnum.h"
#include "LuaBindState.h"
#include "LuaBindVM.h"

namespace LuaBind
{

	//
	// Ö»¶ÁmetatableµÄ__index
	//
	int _rmt__index(lua_State* L)
	{
		// params:
		// 1: enum table
		// 2: key

		// upvalues: 
		// 1: metatable

		int mt = lua_upvalueindex(1);
		lua_pushvalue(L, 2);
		lua_rawget(L, mt);

		return 1;
	}

	int _rmt__newindex(lua_State* L)
	{
		// upvalue: 
		// 1: enum table name

		cc8* name = lua_tostring(L, lua_upvalueindex(1));

		return luaL_error(L, "Enum called \"%s\" is readonly.", name);
	}

	//--------------------------------------------------------------------------------//
#if LUA_BIND_ENABLE_PLAIN_ENUM
	int PlainEnum::registry(lua_State* L)
	{
		// params:
		// 1: enum name
		// 2: metatable

		cc8* name = luaL_checkstring(L, 1);

		if (!lua_istable(L, 2))
		{
			return luaL_error(L, "Create plain enum failed. Require table, but get %s", luaL_typename(L, 2));
		}

		lua_pushvalue(L, -1);
		lua_setfield(L, -2, "__index");

		lua_pushstring(L, name);
		lua_pushcclosure(L, _rmt__newindex, 1);
		lua_setfield(L, -2, "__newindex");

		lua_newtable(L); // enum table

		lua_pushvalue(L, -2); // metatable
		lua_setmetatable(L, -2);

		return 1;
	}
#endif
}