webmcp

view libraries/json/json.c @ 173:f417c4b607ed

Added json.set function to set deep values in a JSON document
author jbe
date Fri Aug 01 18:52:25 2014 +0200 (2014-08-01)
parents a83164390355
children 070edea2a92f
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <math.h>
7 // maximum number of nested JSON values (objects and arrays):
8 // NOTE: The Lua reference states that the stack may typically contain at least
9 // "a few thousand elements". Since every nested level consumes
10 // 3 elements on the Lua stack (the object/array, its shadow table,
11 // a string key or a placeholder), we limit the number of nested levels
12 // to 500. If a stack overflow would still happen in the import function,
13 // this is detected nevertheless and an error is thrown (instead of
14 // returning nil and an error string).
15 #define JSON_MAXDEPTH 500
17 // generate dummy memory addresses that represents null values:
18 char json_nullmark;
19 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
20 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
22 // macros for usage of Lua registry:
23 #define JSON_REGENT char
24 #define JSON_REGPOINTER void *
25 #define json_regpointer(x) (&json_registry.x)
26 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
27 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
28 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
30 // generate dummy memory addresses that represent Lua objects
31 // via lightuserdata keys and LUA_REGISTRYINDEX:
32 static struct {
33 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
34 JSON_REGENT objectmt; // metatable for JSON objects
35 JSON_REGENT arraymt; // metatable for JSON arrays
36 } json_registry;
38 // returns the string "<JSON null marker>":
39 static int json_nullmark_tostring(lua_State *L) {
40 lua_pushliteral(L, "<JSON null marker>");
41 return 1;
42 }
44 #define json_convert_source_idx 1
45 #define json_convert_iterator_idx 2
46 #define json_convert_output_idx 3
47 #define json_convert_shadow_idx 4
48 #define json_convert_iterfun_idx 5
49 #define json_convert_itertbl_idx 6
51 // converts a Lua table to a JSON object or JSON array:
52 // (does never modify the argument, returns an empty object or array if argument is nil)
53 static int json_convert(lua_State *L, int array) {
54 int arrayidx = 0;
55 // determine is argument is given:
56 if (lua_isnoneornil(L, json_convert_source_idx)) {
57 // if no argument is given (or if argument is nil),
58 // create table with shadow table, and leave first table on top of stack:
59 json_regfetch(L, shadowtbl);
60 lua_newtable(L);
61 lua_pushvalue(L, -1);
62 lua_newtable(L);
63 lua_rawset(L, -4);
64 } else {
65 // if an argument was given,
66 // push its iterator function on stack position 2 if existent,
67 // else push null for normal tables:
68 lua_settop(L, 1);
69 if (lua_getmetatable(L, json_convert_source_idx)) {
70 lua_getfield(L, -1, array ? "__ipairs" : "__pairs");
71 if (lua_isnil(L, -1)) luaL_checktype(L, 1, LUA_TTABLE);
72 else if (lua_type(L, -1) != LUA_TFUNCTION)
73 return luaL_error(L, "%s metamethod is not a function", array ? "__ipairs" : "__pairs");
74 lua_replace(L, -2);
75 } else {
76 lua_pushnil(L);
77 }
78 // create result table on stack position 3:
79 lua_newtable(L);
80 // create shadow table on stack position 4:
81 json_regfetch(L, shadowtbl);
82 lua_newtable(L);
83 lua_pushvalue(L, json_convert_output_idx);
84 lua_pushvalue(L, -2);
85 lua_rawset(L, -4);
86 lua_replace(L, -2);
87 // check if iterator function exists:
88 if (lua_isnil(L, json_convert_iterator_idx)) {
89 // if there is no iterator function,
90 // distinguish between objects and arrays:
91 if (array == 0) {
92 // for an object, copy all string key value pairs to shadow table:
93 for (lua_pushnil(L); lua_next(L, json_convert_source_idx); lua_pop(L, 1)) {
94 if (lua_type(L, -2) == LUA_TSTRING) {
95 lua_pushvalue(L, -2);
96 lua_pushvalue(L, -2);
97 lua_rawset(L, json_convert_shadow_idx);
98 }
99 }
100 } else {
101 // for an array, copy consecutive integer value pairs to shadow table:
102 while (1) {
103 // TODO: Lua 5.3 may support more elements
104 if (arrayidx == INT_MAX) {
105 lua_pushnumber(L, (size_t)INT_MAX+1);
106 lua_rawget(L, json_convert_source_idx);
107 if (lua_isnil(L, -1)) break;
108 return luaL_error(L, "Array exceeded length of %d elements", INT_MAX);
109 }
110 arrayidx++;
111 lua_rawgeti(L, json_convert_source_idx, arrayidx);
112 if (lua_isnil(L, -1)) break;
113 lua_rawseti(L, json_convert_shadow_idx, arrayidx);
114 }
115 }
116 } else {
117 // if there is an iterator function,
118 // call iterator function with source value (first argument)
119 // and store 3 result values on stack positions 5 through 7:
120 lua_pushvalue(L, json_convert_iterator_idx);
121 lua_pushvalue(L, 1);
122 lua_call(L, 1, 3);
123 while (1) {
124 lua_pushvalue(L, json_convert_iterfun_idx);
125 lua_pushvalue(L, json_convert_itertbl_idx);
126 lua_pushvalue(L, -3);
127 lua_remove(L, -4);
128 lua_call(L, 2, 2);
129 if (lua_isnil(L, -2)) break;
130 if (lua_type(L, -2) == (array ? LUA_TNUMBER : LUA_TSTRING)) {
131 lua_pushvalue(L, -2);
132 lua_pushvalue(L, -2);
133 lua_rawset(L, json_convert_shadow_idx);
134 }
135 lua_pop(L, 1);
136 }
137 }
138 // let result table be on top of stack:
139 lua_settop(L, json_convert_output_idx);
140 }
141 // set metatable (for result table on top of stack):
142 if (array == 0) json_regfetch(L, objectmt);
143 else json_regfetch(L, arraymt);
144 lua_setmetatable(L, -2);
145 // return table on top of stack:
146 return 1;
147 }
149 static int json_object(lua_State *L) {
150 return json_convert(L, 0);
151 }
153 static int json_array(lua_State *L) {
154 return json_convert(L, 1);
155 }
157 // internal states of JSON parser:
158 #define JSON_STATE_VALUE 0
159 #define JSON_STATE_OBJECT_KEY 1
160 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
161 #define JSON_STATE_OBJECT_VALUE 3
162 #define JSON_STATE_OBJECT_SEPARATOR 4
163 #define JSON_STATE_ARRAY_VALUE 5
164 #define JSON_STATE_ARRAY_SEPARATOR 6
165 #define JSON_STATE_END 7
167 // special Lua stack indicies for json_import function:
168 #define json_import_objectmt_idx 2
169 #define json_import_arraymt_idx 3
170 #define json_import_shadowtbl_idx 4
172 // macros for hex decoding:
173 #define json_utf16_surrogate(x) ((x) >= 0xD800 && (x) <= 0xDFFF)
174 #define json_utf16_lead(x) ((x) >= 0xD800 && (x) <= 0xDBFF)
175 #define json_utf16_tail(x) ((x) >= 0xDC00 && (x) <= 0xDFFF)
176 #define json_import_readhex(x) \
177 do { \
178 x = 0; \
179 for (i=0; i<4; i++) { \
180 x <<= 4; \
181 c = str[pos++]; \
182 if (c >= '0' && c <= '9') x += c - '0'; \
183 else if (c >= 'A' && c <= 'F') x += c - 'A' + 10; \
184 else if (c >= 'a' && c <= 'f') x += c - 'a' + 10; \
185 else if (c == 0) goto json_import_unexpected_eof; \
186 else goto json_import_unexpected_escape; \
187 } \
188 } while (0)
190 // decodes a JSON document:
191 static int json_import(lua_State *L) {
192 int i; // loop variable
193 const char *str; // string to parse
194 size_t total; // total length of string to parse
195 size_t pos = 0; // current position in string to parse
196 size_t level = 0; // nested levels of objects/arrays currently being processed
197 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
198 unsigned char c; // variable to store a single character to be processed (unsigned!)
199 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
200 char *cbuf; // C buffer to decode JSON string values
201 size_t outlen; // maximum length or write position of C buffer
202 long codepoint; // decoded UTF-16 character or higher codepoint
203 long utf16tail; // second decoded UTF-16 character (surrogate tail)
204 size_t arraylen; // variable to temporarily store the array length
205 // require string as argument and convert to C string with length information:
206 str = luaL_checklstring(L, 1, &total);
207 // if string contains a NULL byte, this is a syntax error
208 if (strlen(str) != total) goto json_import_syntax_error;
209 // stack shall contain one function argument:
210 lua_settop(L, 1);
211 // push objectmt onto stack position 2:
212 json_regfetch(L, objectmt);
213 // push arraymt onto stack position 3:
214 json_regfetch(L, arraymt);
215 // push shadowtbl onto stack position 4:
216 json_regfetch(L, shadowtbl);
217 // main loop of parser:
218 json_import_loop:
219 // skip whitespace and store next character in variable 'c':
220 while (c = str[pos],
221 c == ' ' ||
222 c == '\f' ||
223 c == '\n' ||
224 c == '\r' ||
225 c == '\t' ||
226 c == '\v'
227 ) pos++;
228 // NOTE: variable c needs to be unsigned in the following code
229 // switch statement to handle certain (single) characters:
230 switch (c) {
231 // handle end of JSON document:
232 case 0:
233 // if end of JSON document was expected, then return top element of stack as result:
234 if (mode == JSON_STATE_END) return 1;
235 // otherwise, the JSON document was malformed:
236 if (level == 0) {
237 lua_pushnil(L);
238 lua_pushliteral(L, "Empty string");
239 } else {
240 json_import_unexpected_eof:
241 lua_pushnil(L);
242 lua_pushliteral(L, "Unexpected end of JSON document");
243 }
244 return 2;
245 // new JSON object:
246 case '{':
247 // if a JSON object is not expected here, then return an error:
248 if (
249 mode != JSON_STATE_VALUE &&
250 mode != JSON_STATE_OBJECT_VALUE &&
251 mode != JSON_STATE_ARRAY_VALUE
252 ) goto json_import_syntax_error;
253 // create JSON object on stack:
254 lua_newtable(L);
255 // set metatable of JSON object:
256 lua_pushvalue(L, json_import_objectmt_idx);
257 lua_setmetatable(L, -2);
258 // create internal shadow table on stack:
259 lua_newtable(L);
260 // register internal shadow table:
261 lua_pushvalue(L, -2);
262 lua_pushvalue(L, -2);
263 lua_rawset(L, json_import_shadowtbl_idx);
264 // expect object key (or end of object) to follow:
265 mode = JSON_STATE_OBJECT_KEY;
266 // jump to common code for opening JSON object and JSON array:
267 goto json_import_open;
268 // new JSON array:
269 case '[':
270 // if a JSON array is not expected here, then return an error:
271 if (
272 mode != JSON_STATE_VALUE &&
273 mode != JSON_STATE_OBJECT_VALUE &&
274 mode != JSON_STATE_ARRAY_VALUE
275 ) goto json_import_syntax_error;
276 // create JSON array on stack:
277 lua_newtable(L);
278 // set metatable of JSON array:
279 lua_pushvalue(L, json_import_arraymt_idx);
280 lua_setmetatable(L, -2);
281 // create internal shadow table on stack:
282 lua_newtable(L);
283 // register internal shadow table:
284 lua_pushvalue(L, -2);
285 lua_pushvalue(L, -2);
286 lua_rawset(L, json_import_shadowtbl_idx);
287 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
288 lua_pushnil(L);
289 // expect array value (or end of array) to follow:
290 mode = JSON_STATE_ARRAY_VALUE;
291 // continue with common code for opening JSON object and JSON array:
292 // common code for opening JSON object or JSON array:
293 json_import_open:
294 // limit nested levels:
295 if (level >= JSON_MAXDEPTH) {
296 lua_pushnil(L);
297 lua_pushfstring(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
298 return 2;
299 }
300 // additional buffer overflow protection:
301 if (!lua_checkstack(L, LUA_MINSTACK))
302 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
303 // increment level:
304 level++;
305 // consume input character:
306 pos++;
307 goto json_import_loop;
308 // end of JSON object:
309 case '}':
310 // if end of JSON object is not expected here, then return an error:
311 if (
312 mode != JSON_STATE_OBJECT_KEY &&
313 mode != JSON_STATE_OBJECT_SEPARATOR
314 ) goto json_import_syntax_error;
315 // jump to common code for end of JSON object and JSON array:
316 goto json_import_close;
317 // end of JSON array:
318 case ']':
319 // if end of JSON array is not expected here, then return an error:
320 if (
321 mode != JSON_STATE_ARRAY_VALUE &&
322 mode != JSON_STATE_ARRAY_SEPARATOR
323 ) goto json_import_syntax_error;
324 // pop nil key/magic (that was needed to keep stack balance):
325 lua_pop(L, 1);
326 // continue with common code for end of JSON object and JSON array:
327 // common code for end of JSON object or JSON array:
328 json_import_close:
329 // consume input character:
330 pos++;
331 // pop shadow table:
332 lua_pop(L, 1);
333 // check if nested:
334 if (--level) {
335 // if nested,
336 // check if outer(!) structure is an array or object:
337 if (lua_isnil(L, -2)) {
338 // select array value processing:
339 mode = JSON_STATE_ARRAY_VALUE;
340 } else {
341 // select object value processing:
342 mode = JSON_STATE_OBJECT_VALUE;
343 }
344 // store value in outer structure:
345 goto json_import_process_value;
346 }
347 // if not nested, then expect end of JSON document and continue with loop:
348 mode = JSON_STATE_END;
349 goto json_import_loop;
350 // key terminator:
351 case ':':
352 // if key terminator is not expected here, then return an error:
353 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
354 goto json_import_syntax_error;
355 // consume input character:
356 pos++;
357 // expect object value to follow:
358 mode = JSON_STATE_OBJECT_VALUE;
359 // continue with loop:
360 goto json_import_loop;
361 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
362 case ',':
363 // branch according to parser state:
364 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
365 // expect an object key to follow:
366 mode = JSON_STATE_OBJECT_KEY;
367 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
368 // expect an array value to follow:
369 mode = JSON_STATE_ARRAY_VALUE;
370 } else {
371 // if value terminator is not expected here, then return an error:
372 goto json_import_syntax_error;
373 }
374 // consume input character:
375 pos++;
376 // continue with loop:
377 goto json_import_loop;
378 // string literal:
379 case '"':
380 // consume quote character:
381 pos++;
382 // find last character in input string:
383 outlen = pos;
384 while ((c = str[outlen]) != '"') {
385 // consume one character:
386 outlen++;
387 // handle unexpected end of JSON document:
388 if (c == 0) goto json_import_unexpected_eof;
389 // consume one extra character when encountering an escaped quote:
390 else if (c == '\\' && str[outlen] == '"') outlen++;
391 }
392 // determine buffer length:
393 outlen -= pos;
394 // check if string is non empty:
395 if (outlen) {
396 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
397 cbuf = luaL_buffinitsize(L, &luabuf, outlen);
398 outlen = 0;
399 // loop through the characters until encountering end quote:
400 while ((c = str[pos++]) != '"') {
401 // NOTE: unexpected end cannot happen anymore
402 if (c < 32 || c == 127) {
403 // do not allow ASCII control characters:
404 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
405 // by this parser to allow different encodings than Unicode
406 lua_pushnil(L);
407 lua_pushliteral(L, "Unexpected control character in JSON string");
408 return 2;
409 } else if (c == '\\') {
410 // read next char after backslash escape:
411 c = str[pos++];
412 switch (c) {
413 // unexpected end-of-string:
414 case 0:
415 goto json_import_unexpected_eof;
416 // unescaping of quotation mark, slash, and backslash:
417 case '"':
418 case '/':
419 case '\\':
420 cbuf[outlen++] = c;
421 break;
422 // unescaping of backspace:
423 case 'b': cbuf[outlen++] = '\b'; break;
424 // unescaping of form-feed:
425 case 'f': cbuf[outlen++] = '\f'; break;
426 // unescaping of new-line:
427 case 'n': cbuf[outlen++] = '\n'; break;
428 // unescaping of carriage-return:
429 case 'r': cbuf[outlen++] = '\r'; break;
430 // unescaping of tabulator:
431 case 't': cbuf[outlen++] = '\t'; break;
432 // unescaping of UTF-16 characters
433 case 'u':
434 // decode 4 hex nibbles:
435 json_import_readhex(codepoint);
436 // handle surrogate character:
437 if (json_utf16_surrogate(codepoint)) {
438 // check if first surrogate is in valid range:
439 if (json_utf16_lead(codepoint)) {
440 // require second surrogate:
441 if ((c = str[pos++]) != '\\' || (c = str[pos++]) != 'u') {
442 if (c == 0) goto json_import_unexpected_eof;
443 else goto json_import_wrong_surrogate;
444 }
445 // read 4 hex nibbles of second surrogate character:
446 json_import_readhex(utf16tail);
447 // check if second surrogate is in valid range:
448 if (!json_utf16_tail(utf16tail)) goto json_import_wrong_surrogate;
449 // calculate codepoint:
450 codepoint = 0x10000 + (utf16tail - 0xDC00) + (codepoint - 0xD800) * 0x400;
451 } else {
452 // throw error for wrong surrogates:
453 json_import_wrong_surrogate:
454 lua_pushnil(L);
455 lua_pushliteral(L, "Illegal UTF-16 surrogate in JSON string escape sequence");
456 return 2;
457 }
458 }
459 // encode as UTF-8:
460 if (codepoint < 0x80) {
461 cbuf[outlen++] = (char)codepoint;
462 } else if (codepoint < 0x800) {
463 cbuf[outlen++] = (char)(0xc0 | (codepoint >> 6));
464 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
465 } else if (codepoint < 0x10000) {
466 cbuf[outlen++] = (char)(0xe0 | (codepoint >> 12));
467 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
468 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
469 } else {
470 cbuf[outlen++] = (char)(0xf0 | (codepoint >> 18));
471 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
472 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
473 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
474 }
475 break;
476 // unexpected escape sequence:
477 default:
478 json_import_unexpected_escape:
479 lua_pushnil(L);
480 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
481 return 2;
482 }
483 } else {
484 // normal character:
485 cbuf[outlen++] = c;
486 }
487 }
488 // process buffer to Lua string:
489 luaL_pushresultsize(&luabuf, outlen);
490 } else {
491 // if JSON string is empty,
492 // push empty Lua string:
493 lua_pushliteral(L, "");
494 // consume closing quote:
495 pos++;
496 }
497 // continue with processing of decoded string:
498 goto json_import_process_value;
499 }
500 // process values whose type is is not deducible from a single character:
501 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
502 // for numbers,
503 // use strtod() call to parse a (double precision) floating point number:
504 double numval;
505 char *endptr;
506 numval = strtod(str+pos, &endptr);
507 // catch parsing errors:
508 if (endptr == str+pos) goto json_import_syntax_error;
509 // consume characters that were parsed:
510 pos += endptr - (str+pos);
511 // push parsed (double precision) floating point number on Lua stack:
512 lua_pushnumber(L, numval);
513 } else if (!strncmp(str+pos, "true", 4)) {
514 // consume 4 input characters for "true":
515 pos += 4;
516 // put Lua true value onto stack:
517 lua_pushboolean(L, 1);
518 } else if (!strncmp(str+pos, "false", 5)) {
519 // consume 5 input characters for "false":
520 pos += 5;
521 // put Lua false value onto stack:
522 lua_pushboolean(L, 0);
523 } else if (!strncmp(str+pos, "null", 4)) {
524 // consume 4 input characters for "null":
525 pos += 4;
526 // different behavor for top-level and sub-levels:
527 if (level) {
528 // if sub-level,
529 // push special null-marker onto stack:
530 json_pushnullmark(L);
531 } else {
532 // if top-level,
533 // push nil onto stack:
534 lua_pushnil(L);
535 }
536 } else {
537 // all other cases are a syntax error:
538 goto json_import_syntax_error;
539 }
540 // process a decoded value or key value pair (expected on top of Lua stack):
541 json_import_process_value:
542 switch (mode) {
543 // an object key has been read:
544 case JSON_STATE_OBJECT_KEY:
545 // if an object key is not a string, then this is a syntax error:
546 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
547 // expect key terminator to follow:
548 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
549 // continue with loop:
550 goto json_import_loop;
551 // a key value pair has been read:
552 case JSON_STATE_OBJECT_VALUE:
553 // store key value pair in outer shadow table:
554 lua_rawset(L, -3);
555 // expect value terminator (or end of object) to follow:
556 mode = JSON_STATE_OBJECT_SEPARATOR;
557 // continue with loop:
558 goto json_import_loop;
559 // an array value has been read:
560 case JSON_STATE_ARRAY_VALUE:
561 // get current array length:
562 arraylen = lua_rawlen(L, -3);
563 // throw error if array would exceed INT_MAX elements:
564 // TODO: Lua 5.3 may support more elements
565 if (arraylen >= INT_MAX) {
566 lua_pushnil(L);
567 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
568 }
569 // store value in outer shadow table:
570 lua_rawseti(L, -3, arraylen + 1);
571 // expect value terminator (or end of object) to follow:
572 mode = JSON_STATE_ARRAY_SEPARATOR;
573 // continue with loop
574 goto json_import_loop;
575 // a single value has been read:
576 case JSON_STATE_VALUE:
577 // leave value on top of stack, expect end of JSON document, and continue with loop:
578 mode = JSON_STATE_END;
579 goto json_import_loop;
580 }
581 // syntax error handling (reachable by goto statement):
582 json_import_syntax_error:
583 lua_pushnil(L);
584 lua_pushliteral(L, "Syntax error in JSON document");
585 return 2;
586 }
588 // special Lua stack indicies for json_path function:
589 #define json_path_shadowtbl_idx 1
591 // stack offset of arguments to json_path function:
592 #define json_path_idxshift 1
594 // gets a value or its type from a JSON document (passed as first argument)
595 // using a path (passed as variable number of keys after first argument):
596 static int json_path(lua_State *L, int type_mode) {
597 int stacktop; // stack index of top of stack (after shifting)
598 int idx = 2 + json_path_idxshift; // stack index of current argument to process
599 // require at least one argument:
600 luaL_checkany(L, 1);
601 // insert shadowtbl into stack at position 1 (shifting the arguments):
602 json_regfetch(L, shadowtbl);
603 lua_insert(L, 1);
604 // store stack index of top of stack:
605 stacktop = lua_gettop(L);
606 // use first argument as "current value" (stored on top of stack):
607 lua_pushvalue(L, 1 + json_path_idxshift);
608 // process each "path key" (2nd argument and following arguments):
609 while (idx <= stacktop) {
610 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
611 if (lua_isnil(L, -1)) return 1;
612 // try to get shadow table of "current value":
613 lua_pushvalue(L, -1);
614 lua_rawget(L, json_path_shadowtbl_idx);
615 if (lua_isnil(L, -1)) {
616 // if no shadow table is found,
617 if (lua_type(L, -1) == LUA_TTABLE) {
618 // and if "current value" is a table,
619 // drop nil from stack:
620 lua_pop(L, 1);
621 // get "next value" using the "path key":
622 lua_pushvalue(L, idx++);
623 lua_gettable(L, -2);
624 } else {
625 // if "current value" is not a table,
626 // then the path cannot be walked and nil (already on top of stack) is returned:
627 return 1;
628 }
629 } else {
630 // if a shadow table is found,
631 // set "current value" to its shadow table:
632 lua_replace(L, -2);
633 // get "next value" using the "path key":
634 lua_pushvalue(L, idx++);
635 lua_rawget(L, -2);
636 }
637 // the "next value" replaces the "current value":
638 lua_replace(L, -2);
639 }
640 if (!type_mode) {
641 // if a value (and not its type) was requested,
642 // check if value is the null-marker, and store nil on top of Lua stack in that case:
643 if (json_isnullmark(L, -1)) lua_pushnil(L);
644 } else {
645 // if the type was requested,
646 // check if value is the null-marker:
647 if (json_isnullmark(L, -1)) {
648 // if yes, store string "null" on top of Lua stack:
649 lua_pushliteral(L, "null");
650 } else {
651 // otherwise,
652 // check if metatable indicates "object" or "array":
653 if (lua_getmetatable(L, -1)) {
654 json_regfetch(L, objectmt);
655 if (lua_rawequal(L, -2, -1)) {
656 // if value has metatable for JSON objects,
657 // return string "object":
658 lua_pushliteral(L, "object");
659 return 1;
660 }
661 json_regfetch(L, arraymt);
662 if (lua_rawequal(L, -3, -1)) {
663 // if value has metatable for JSON arrays,
664 // return string "object":
665 lua_pushliteral(L, "array");
666 return 1;
667 }
668 // remove 3 metatables (one of the value, two for comparison) from stack:
669 lua_pop(L, 3);
670 }
671 // otherwise, get the Lua type:
672 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
673 }
674 }
675 // return the top most value on the Lua stack:
676 return 1;
677 }
679 // gets a value from a JSON document (passed as first argument)
680 // using a path (passed as variable number of keys after first argument):
681 static int json_get(lua_State *L) {
682 return json_path(L, 0);
683 }
685 // gets a value's type from a JSON document (passed as first argument)
686 // using a path (variable number of keys after first argument):
687 static int json_type(lua_State *L) {
688 return json_path(L, 1);
689 }
691 // special Lua stack indicies for json_set function:
692 #define json_set_shadowtbl_idx 1
693 #define json_set_objectmt_idx 2
694 #define json_set_arraymt_idx 3
696 // stack offset of arguments to json_set function:
697 #define json_set_idxshift 3
699 // sets a value (passed as second argument) in a JSON document (passed as first argument)
700 // using a path (variable number of keys starting at third argument):
701 static int json_set(lua_State *L) {
702 int stacktop; // stack index of top of stack (after shifting)
703 int idx = 3; // stack index of current argument to process
704 // require at least two arguments:
705 luaL_checkany(L, 1);
706 luaL_checkany(L, 2);
707 // insert shadowtbl into stack at position 1 (shifting the arguments):
708 json_regfetch(L, shadowtbl);
709 lua_insert(L, 1);
710 // insert objectmt into stack at position 2 (shifting the arguments):
711 json_regfetch(L, objectmt);
712 lua_insert(L, 2);
713 // insert arraymt into stack at position 3 (shifting the arguments):
714 json_regfetch(L, arraymt);
715 lua_insert(L, 3);
716 // store stack index of top of stack:
717 stacktop = lua_gettop(L);
718 // use nil as initial "parent value":
719 lua_pushnil(L);
720 // use first argument as "current value":
721 lua_pushvalue(L, 1 + json_set_idxshift);
722 // set all necessary values in path:
723 for (idx = 3 + json_set_idxshift; idx<=stacktop; idx++) {
724 // push metatable of "current value" onto stack:
725 if (!lua_getmetatable(L, -1)) lua_pushnil(L);
726 // distinguish according to type of path key:
727 switch (lua_type(L, idx)) {
728 case LUA_TSTRING:
729 // if path key is a string,
730 // check if "current value" is a JSON object (or table without metatable):
731 if (
732 lua_rawequal(L, -1, json_set_objectmt_idx) ||
733 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
734 ) {
735 // if "current value" is acceptable,
736 // pop metatable and leave "current value" on top of stack:
737 lua_pop(L, 1);
738 } else {
739 // if "current value" is not acceptable:
740 // pop metatable and "current value":
741 lua_pop(L, 2);
742 // throw error if parent element does not exist:
743 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON object");
744 // push new JSON object as "current value" onto stack:
745 lua_newtable(L);
746 // create and register shadow table:
747 lua_pushvalue(L, -1);
748 lua_newtable(L);
749 lua_rawset(L, json_set_shadowtbl_idx);
750 // set metatable of JSON object:
751 lua_pushvalue(L, json_set_objectmt_idx);
752 lua_setmetatable(L, -2);
753 // set entry in "parent value":
754 lua_pushvalue(L, idx-1);
755 lua_pushvalue(L, -2);
756 lua_settable(L, -4);
757 }
758 break;
759 case LUA_TNUMBER:
760 // if path key is a number,
761 // check if "current value" is a JSON array (or table without metatable):
762 if (
763 lua_rawequal(L, -1, json_set_arraymt_idx) ||
764 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
765 ) {
766 // if "current value" is acceptable,
767 // pop metatable and leave "current value" on top of stack:
768 lua_pop(L, 1);
769 } else {
770 // if "current value" is not acceptable:
771 // pop metatable and "current value":
772 lua_pop(L, 2);
773 // throw error if parent element does not exist:
774 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON array");
775 // push new JSON array as "current value" onto stack:
776 lua_newtable(L);
777 // create and register shadow table:
778 lua_pushvalue(L, -1);
779 lua_newtable(L);
780 lua_rawset(L, json_set_shadowtbl_idx);
781 // set metatable of JSON array:
782 lua_pushvalue(L, json_set_arraymt_idx);
783 lua_setmetatable(L, -2);
784 // set entry in "parent value":
785 lua_pushvalue(L, idx-1);
786 lua_pushvalue(L, -2);
787 lua_settable(L, -4);
788 }
789 break;
790 default:
791 return luaL_error(L, "Invalid path key of type %s", lua_typename(L, lua_type(L, idx)));
792 }
793 // check if last path element is being processed:
794 if (idx == stacktop) {
795 // if the last path element is being processed,
796 // set last path value in "current value" container:
797 lua_pushvalue(L, idx);
798 lua_pushvalue(L, 2 + json_set_idxshift);
799 lua_settable(L, -3);
800 } else {
801 // if the processed path element is not the last,
802 // use old "current value" as new "parent value"
803 lua_remove(L, -2);
804 // push new "current value" onto stack by performing a lookup:
805 lua_pushvalue(L, idx);
806 lua_gettable(L, -2);
807 }
808 }
809 // return first argument for convenience:
810 lua_settop(L, 1 + json_set_idxshift);
811 return 1;
812 }
814 // returns the length of a JSON array (or zero for a table without numeric keys):
815 static int json_len(lua_State *L) {
816 // stack shall contain one function argument:
817 lua_settop(L, 1);
818 // try to get corresponding shadow table for first argument:
819 json_regfetch(L, shadowtbl);
820 lua_pushvalue(L, 1);
821 lua_rawget(L, -2);
822 // if shadow table does not exist, return length of argument, else length of shadow table:
823 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
824 return 1;
825 }
827 static int json_index(lua_State *L) {
828 // stack shall contain two function arguments:
829 lua_settop(L, 2);
830 // get corresponding shadow table for first argument:
831 json_regfetch(L, shadowtbl);
832 lua_pushvalue(L, 1);
833 lua_rawget(L, -2);
834 // throw error if no shadow table was found:
835 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
836 // use key passed as second argument to lookup value in shadow table:
837 lua_pushvalue(L, 2);
838 lua_rawget(L, -2);
839 // if value is null-marker, then push nil onto stack:
840 if (json_isnullmark(L, -1)) lua_pushnil(L);
841 // return either looked up value, or nil
842 return 1;
843 }
845 static int json_newindex(lua_State *L) {
846 // stack shall contain three function arguments:
847 lua_settop(L, 3);
848 // get corresponding shadow table for first argument:
849 json_regfetch(L, shadowtbl);
850 lua_pushvalue(L, 1);
851 lua_rawget(L, -2);
852 // throw error if no shadow table was found:
853 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
854 // replace first argument with shadow table:
855 lua_replace(L, 1);
856 // reset stack and use second and third argument to write to shadow table:
857 lua_settop(L, 3);
858 lua_rawset(L, 1);
859 // return nothing:
860 return 0;
861 }
863 static int json_pairs_iterfunc(lua_State *L) {
864 // stack shall contain two function arguments:
865 lua_settop(L, 2);
866 // get corresponding shadow table for first argument:
867 json_regfetch(L, shadowtbl);
868 lua_pushvalue(L, 1);
869 lua_rawget(L, -2);
870 // throw error if no shadow table was found:
871 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
872 // get next key value pair from shadow table (using previous key from argument 2)
873 // and return nothing if there is no next pair:
874 lua_pushvalue(L, 2);
875 if (!lua_next(L, -2)) return 0;
876 // replace null-marker with nil:
877 if (json_isnullmark(L, -1)) {
878 lua_pop(L, 1);
879 lua_pushnil(L);
880 }
881 // return key and value (or key and nil, if null-marker was found):
882 return 2;
883 }
885 // returns a triple such that 'for key, value in pairs(obj) do ... end'
886 // iterates through all key value pairs (including JSON null keys represented as Lua nil):
887 static int json_pairs(lua_State *L) {
888 // require one argument to function
889 luaL_checkany(L, 1);
890 // return triple of function json_pairs_iterfunc, first argument, and nil:
891 lua_pushcfunction(L, json_pairs_iterfunc);
892 lua_pushvalue(L, 1);
893 lua_pushnil(L);
894 return 3;
895 }
897 static int json_ipairs_iterfunc(lua_State *L) {
898 lua_Integer idx;
899 // stack shall contain two function arguments:
900 lua_settop(L, 2);
901 // calculate new index by incrementing second argument:
902 idx = lua_tointeger(L, 2) + 1;
903 // get corresponding shadow table for first argument:
904 json_regfetch(L, shadowtbl);
905 lua_pushvalue(L, 1);
906 lua_rawget(L, -2);
907 // throw error if no shadow table was found:
908 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
909 // do integer lookup in shadow table:
910 lua_rawgeti(L, -1, idx);
911 // return nothing if there was no value:
912 if (lua_isnil(L, -1)) return 0;
913 // return new index and
914 // either the looked up value if it is not equal to the null-marker
915 // or nil instead of null-marker:
916 lua_pushinteger(L, idx);
917 if (json_isnullmark(L, -2)) lua_pushnil(L);
918 else lua_pushvalue(L, -2);
919 return 2;
920 }
922 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
923 // iterates through all values (including JSON null represented as Lua nil):
924 static int json_ipairs(lua_State *L) {
925 // require one argument to function
926 luaL_checkany(L, 1);
927 // return triple of function json_ipairs_iterfunc, first argument, and zero:
928 lua_pushcfunction(L, json_ipairs_iterfunc);
929 lua_pushvalue(L, 1);
930 lua_pushinteger(L, 0);
931 return 3;
932 }
934 typedef struct {
935 size_t length;
936 const char *data;
937 } json_key_t;
939 static int json_key_cmp(json_key_t *key1, json_key_t *key2) {
940 size_t pos = 0;
941 unsigned char c1, c2;
942 while (1) {
943 if (key1->length > pos) {
944 if (key2->length > pos) {
945 c1 = key1->data[pos];
946 c2 = key2->data[pos];
947 if (c1 < c2) return -1;
948 else if (c1 > c2) return 1;
949 } else {
950 return 1;
951 }
952 } else {
953 if (key2->length > pos) {
954 return -1;
955 } else {
956 return 0;
957 }
958 }
959 pos++;
960 }
961 }
963 #define JSON_TABLETYPE_UNKNOWN 0
964 #define JSON_TABLETYPE_OBJECT 1
965 #define JSON_TABLETYPE_ARRAY 2
967 #define json_export_internal_indentstring_idx 1
968 #define json_export_internal_level_idx 2
969 #define json_export_internal_value_idx 3
970 #define json_export_internal_tmp_idx 4
972 static int json_export_internal(lua_State *L) {
973 int level;
974 int pretty;
975 int i;
976 lua_Number num;
977 const char *str;
978 unsigned char c;
979 size_t strlen;
980 size_t pos = 0;
981 luaL_Buffer buf;
982 char hexcode[7]; // backslash, character 'u', 4 hex digits, and terminating NULL byte
983 int tabletype = JSON_TABLETYPE_UNKNOWN;
984 int anyelement = 0;
985 size_t keycount = 0;
986 size_t keypos = 0;
987 json_key_t *keybuf = NULL;
988 lua_Integer idx;
989 lua_settop(L, json_export_internal_value_idx);
990 if (json_isnullmark(L, json_export_internal_value_idx)) {
991 lua_pop(L, 1);
992 lua_pushnil(L);
993 }
994 switch (lua_type(L, json_export_internal_value_idx)) {
995 case LUA_TNIL:
996 lua_pushliteral(L, "null");
997 return 1;
998 case LUA_TNUMBER:
999 num = lua_tonumber(L, json_export_internal_value_idx);
1000 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
1001 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
1002 lua_tostring(L, json_export_internal_value_idx);
1003 return 1;
1004 case LUA_TBOOLEAN:
1005 if (lua_toboolean(L, json_export_internal_value_idx)) {
1006 lua_pushliteral(L, "true");
1007 } else {
1008 lua_pushliteral(L, "false");
1010 return 1;
1011 case LUA_TSTRING:
1012 str = lua_tolstring(L, 3, &strlen);
1013 luaL_buffinit(L, &buf);
1014 luaL_addchar(&buf, '"');
1015 while (pos < strlen) {
1016 c = str[pos++];
1017 if (c == '"') luaL_addstring(&buf, "\\\"");
1018 else if (c == '\\') luaL_addstring(&buf, "\\\\");
1019 else if (c == 127) luaL_addstring(&buf, "\\u007F");
1020 else if (c >= 32) luaL_addchar(&buf, c);
1021 else if (c == '\b') luaL_addstring(&buf, "\\b");
1022 else if (c == '\f') luaL_addstring(&buf, "\\f");
1023 else if (c == '\n') luaL_addstring(&buf, "\\n");
1024 else if (c == '\r') luaL_addstring(&buf, "\\r");
1025 else if (c == '\t') luaL_addstring(&buf, "\\t");
1026 else if (c == '\v') luaL_addstring(&buf, "\\v");
1027 else {
1028 sprintf(hexcode, "\\u%04X", c);
1029 luaL_addstring(&buf, hexcode);
1032 luaL_addchar(&buf, '"');
1033 luaL_pushresult(&buf);
1034 return 1;
1035 case LUA_TTABLE:
1036 if (lua_getmetatable(L, json_export_internal_value_idx)) {
1037 json_regfetch(L, objectmt);
1038 if (lua_rawequal(L, -2, -1)) {
1039 tabletype = JSON_TABLETYPE_OBJECT;
1040 } else {
1041 json_regfetch(L, arraymt);
1042 if (lua_rawequal(L, -3, -1)) {
1043 tabletype = JSON_TABLETYPE_ARRAY;
1044 } else {
1045 return luaL_error(L, "JSON export not possible for tables with nonsupported metatable");
1049 json_regfetch(L, shadowtbl);
1050 lua_pushvalue(L, json_export_internal_value_idx);
1051 lua_rawget(L, -2);
1052 if (!lua_isnil(L, -1)) lua_replace(L, json_export_internal_value_idx);
1053 lua_settop(L, json_export_internal_value_idx);
1054 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
1055 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1056 switch (lua_type(L, -2)) {
1057 case LUA_TSTRING:
1058 keycount++;
1059 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_OBJECT;
1060 else if (tabletype == JSON_TABLETYPE_ARRAY) goto json_export_tabletype_error;
1061 break;
1062 case LUA_TNUMBER:
1063 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_ARRAY;
1064 else if (tabletype == JSON_TABLETYPE_OBJECT) goto json_export_tabletype_error;
1065 break;
1069 pretty = lua_toboolean(L, json_export_internal_indentstring_idx);
1070 level = lua_tointeger(L, json_export_internal_level_idx) + 1;
1071 if (level > JSON_MAXDEPTH) {
1072 return luaL_error(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
1074 switch (tabletype) {
1075 case JSON_TABLETYPE_OBJECT:
1076 if (!keycount) {
1077 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1078 if (lua_type(L, -2) == LUA_TSTRING) keycount++;
1081 if (keycount) {
1082 keybuf = calloc(keycount, sizeof(json_key_t));
1083 if (!keybuf) return luaL_error(L, "Memory allocation failed in JSON library");
1084 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1085 if (lua_type(L, -2) == LUA_TSTRING) {
1086 json_key_t *key = keybuf + (keypos++);
1087 key->data = lua_tolstring(L, -2, &key->length);
1090 qsort(keybuf, keycount, sizeof(json_key_t), (void *)json_key_cmp);
1092 luaL_buffinit(L, &buf);
1093 luaL_addchar(&buf, '{');
1094 for (keypos=0; keypos<keycount; keypos++) {
1095 json_key_t *key = keybuf + keypos;
1096 if (keypos) luaL_addchar(&buf, ',');
1097 if (pretty) {
1098 luaL_addchar(&buf, '\n');
1099 for (i=0; i<level; i++) {
1100 lua_pushvalue(L, json_export_internal_indentstring_idx);
1101 luaL_addvalue(&buf);
1104 lua_pushcfunction(L, json_export_internal);
1105 lua_pushvalue(L, json_export_internal_indentstring_idx);
1106 lua_pushinteger(L, level);
1107 lua_pushlstring(L, key->data, key->length);
1108 if (lua_pcall(L, 3, 1, 0)) {
1109 if (keybuf) free(keybuf);
1110 return lua_error(L);
1112 luaL_addvalue(&buf);
1113 luaL_addchar(&buf, ':');
1114 if (pretty) luaL_addchar(&buf, ' ');
1115 lua_pushcfunction(L, json_export_internal);
1116 lua_pushvalue(L, json_export_internal_indentstring_idx);
1117 lua_pushinteger(L, level);
1118 lua_pushlstring(L, key->data, key->length);
1119 lua_rawget(L, json_export_internal_value_idx);
1120 if (lua_pcall(L, 3, 1, 0)) {
1121 if (keybuf) free(keybuf);
1122 return lua_error(L);
1124 luaL_addvalue(&buf);
1126 if (keybuf) free(keybuf);
1127 if (pretty && keycount != 0) {
1128 luaL_addchar(&buf, '\n');
1129 for (i=0; i<level-1; i++) {
1130 lua_pushvalue(L, json_export_internal_indentstring_idx);
1131 luaL_addvalue(&buf);
1134 luaL_addchar(&buf, '}');
1135 if (pretty && level == 1) luaL_addchar(&buf, '\n');
1136 luaL_pushresult(&buf);
1137 return 1;
1138 case JSON_TABLETYPE_ARRAY:
1139 lua_settop(L, json_export_internal_tmp_idx);
1140 luaL_buffinit(L, &buf);
1141 luaL_addchar(&buf, '[');
1142 for (idx = 1; ; idx++) {
1143 lua_rawgeti(L, json_export_internal_value_idx, idx);
1144 if (lua_isnil(L, -1)) {
1145 lua_pop(L, 1);
1146 break;
1148 lua_replace(L, json_export_internal_tmp_idx);
1149 if (anyelement) luaL_addchar(&buf, ',');
1150 anyelement = 1;
1151 if (pretty) {
1152 luaL_addchar(&buf, '\n');
1153 for (i=0; i<level; i++) {
1154 lua_pushvalue(L, json_export_internal_indentstring_idx);
1155 luaL_addvalue(&buf);
1158 lua_pushcfunction(L, json_export_internal);
1159 lua_pushvalue(L, json_export_internal_indentstring_idx);
1160 lua_pushinteger(L, level);
1161 lua_pushvalue(L, json_export_internal_tmp_idx);
1162 lua_call(L, 3, 1);
1163 luaL_addvalue(&buf);
1165 if (pretty && anyelement) {
1166 luaL_addchar(&buf, '\n');
1167 for (i=0; i<level-1; i++) {
1168 lua_pushvalue(L, json_export_internal_indentstring_idx);
1169 luaL_addvalue(&buf);
1172 luaL_addchar(&buf, ']');
1173 if (pretty && level == 1) luaL_addchar(&buf, '\n');
1174 luaL_pushresult(&buf);
1175 return 1;
1177 json_export_tabletype_error:
1178 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
1180 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, json_export_internal_value_idx)));
1183 static int json_export(lua_State *L) {
1184 lua_settop(L, 1);
1185 lua_pushcfunction(L, json_export_internal);
1186 lua_pushnil(L);
1187 lua_pushinteger(L, 0);
1188 lua_pushvalue(L, 1);
1189 lua_call(L, 3, 1);
1190 return 1;
1193 static int json_pretty(lua_State *L) {
1194 lua_settop(L, 2);
1195 lua_pushcfunction(L, json_export_internal);
1196 if (lua_isnil(L, 2)) lua_pushliteral(L, " ");
1197 else lua_pushvalue(L, 2);
1198 lua_pushinteger(L, 0);
1199 lua_pushvalue(L, 1);
1200 lua_call(L, 3, 1);
1201 return 1;
1204 // functions in library module:
1205 static const struct luaL_Reg json_module_functions[] = {
1206 {"object", json_object},
1207 {"array", json_array},
1208 {"import", json_import},
1209 {"export", json_export},
1210 {"pretty", json_pretty},
1211 {"get", json_get},
1212 {"type", json_type},
1213 {"set", json_set},
1214 {NULL, NULL}
1215 };
1217 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
1218 static const struct luaL_Reg json_metatable_functions[] = {
1219 {"__len", json_len},
1220 {"__index", json_index},
1221 {"__newindex", json_newindex},
1222 {"__pairs", json_pairs},
1223 {"__ipairs", json_ipairs},
1224 {"__tostring", json_export},
1225 {NULL, NULL}
1226 };
1228 // metamethods for JSON null marker:
1229 static const struct luaL_Reg json_nullmark_metamethods[] = {
1230 {"__tostring", json_nullmark_tostring},
1231 {NULL, NULL}
1232 };
1234 // initializes json library:
1235 int luaopen_json(lua_State *L) {
1236 // empty stack:
1237 lua_settop(L, 0);
1238 // push library module onto stack position 1:
1239 lua_newtable(L);
1240 // register library functions:
1241 luaL_setfuncs(L, json_module_functions, 0);
1242 // create and store objectmt:
1243 lua_newtable(L);
1244 luaL_setfuncs(L, json_metatable_functions, 0);
1245 json_regstore(L, objectmt);
1246 // create and store arraymt:
1247 lua_newtable(L);
1248 luaL_setfuncs(L, json_metatable_functions, 0);
1249 json_regstore(L, arraymt);
1250 // create and store ephemeron table to store shadow tables for each JSON object/array
1251 // to allow NULL values returned as nil
1252 lua_newtable(L);
1253 lua_newtable(L); // metatable for ephemeron table
1254 lua_pushliteral(L, "__mode");
1255 lua_pushliteral(L, "k");
1256 lua_rawset(L, -3);
1257 lua_setmetatable(L, -2);
1258 json_regstore(L, shadowtbl);
1259 // set metatable of null marker and make it available through library module:
1260 json_pushnullmark(L);
1261 lua_newtable(L);
1262 luaL_setfuncs(L, json_nullmark_metamethods, 0);
1263 lua_setmetatable(L, -2);
1264 lua_setfield(L, 1, "null");
1265 // return library module (that's expected on top of stack):
1266 return 1;

Impressum / About Us