summaryrefslogtreecommitdiff
path: root/plugins/MirLua/Modules/m_json/src/metatable.cpp
blob: b7b1c37f2466231aeb8c967e07352174f5e3faf1 (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
111
112
113
114
115
116
117
118
119
120
#include "stdafx.h"

void lua2json(lua_State *L, JSONNode &node)
{
	const char *name = lua_tostring(L, -2);

	switch (lua_type(L, -1))
	{
	case LUA_TNIL:
		node.nullify();
		break;
	case LUA_TSTRING:
		node = lua_tostring(L, -1);
		break;
	case LUA_TBOOLEAN:
		node = lua_toboolean(L, -1) != 0;
		break;
	case LUA_TNUMBER:
		node = lua_tonumber(L, -1);
		break;
	case LUA_TTABLE:
	{
		node.cast(JSON_NODE);
		if (name)
			node.set_name(name);

		lua_pushnil(L);
		while (lua_next(L, -2) != 0)
		{
			JSONNode child;
			lua2json(L, child);
			node << child;

			lua_pop(L, 1);
		}
	}
	}
}

static int json__index(lua_State *L)
{
	JSONNode &node = *((JSON*)luaL_checkudata(L, 1, MT_JSON))->node;

	switch (node.type())
	{
	case JSON_NULL:
		lua_pushnil(L);
		break;
	case JSON_STRING:
		lua_pushstring(L, node.as_string().c_str());
		break;
	case JSON_NUMBER:
		lua_pushnumber(L, node.as_int());
		break;
	case JSON_BOOL:
		lua_pushboolean(L, node.as_bool());
		break;
	case JSON_NODE:
	case JSON_ARRAY:
		new (L) JSONNode(node);
		luaL_setmetatable(L, MT_JSON);
	}

	return 1;
}

static int json__newindex(lua_State *L)
{
	JSONNode &node = *((JSON*)luaL_checkudata(L, 1, MT_JSON))->node;
	const char *key = lua_tostring(L, 2);

	JSONNode child = node[key];
	if (child.isnull())
	{
		child.set_name(key);
		node << child;
	}
	lua2json(L, child);
	node[key] = child;

	return 0;
}

static int json__len(lua_State *L)
{
	JSONNode &node = *((JSON*)luaL_checkudata(L, 1, MT_JSON))->node;

	lua_pushnumber(L, node.size());

	return 1;
}

static int json__tostring(lua_State *L)
{
	JSONNode &node = *((JSON*)luaL_checkudata(L, 1, MT_JSON))->node;

	lua_pushstring(L, node.write().c_str());

	return 1;
}

static int json__gc(lua_State *L)
{
	JSON *json = (JSON*)luaL_checkudata(L, 1, MT_JSON);

	delete json;

	return 0;
}

static const struct luaL_Reg jsonApi[] =
{
	{ "__index", json__index },
	{ "__newindex", json__newindex },
	{ "__len", json__len },
	{ "__tostring", json__tostring },
	{ "__gc", json__gc },

	{ NULL, NULL }
};