MCPcopy Create free account
hub / github.com/OpenTTD/OpenTTD / ScriptAdminMakeJSON

Function ScriptAdminMakeJSON

src/script/api/script_admin.cpp:31–117  ·  view source on GitHub ↗

* Convert a Squirrel structure into a JSON object. * * This function is not "static", so it can be tested in unittests. * * @param json The resulting JSON object. * @param vm The VM to operate on. * @param index The index we are currently working for. * @param depth The current depth in the squirrel struct. * @return True iff the conversion was successful. */

Source from the content-addressed store, hash-verified

29 * @return True iff the conversion was successful.
30 */
31bool ScriptAdminMakeJSON(nlohmann::json &json, HSQUIRRELVM vm, SQInteger index, int depth = 0)
32{
33 if (depth == SQUIRREL_MAX_DEPTH) {
34 ScriptLog::Error("Send parameters can only be nested to 25 deep. No data sent."); // SQUIRREL_MAX_DEPTH = 25
35 return false;
36 }
37
38 switch (sq_gettype(vm, index)) {
39 case OT_INTEGER: {
40 SQInteger res;
41 sq_getinteger(vm, index, &res);
42
43 json = res;
44 return true;
45 }
46
47 case OT_STRING: {
48 std::string_view view;
49 sq_getstring(vm, index, view);
50
51 json = view;
52 return true;
53 }
54
55 case OT_ARRAY: {
56 json = nlohmann::json::array();
57
58 sq_pushnull(vm);
59 while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
60 nlohmann::json tmp;
61
62 bool res = ScriptAdminMakeJSON(tmp, vm, -1, depth + 1);
63 sq_pop(vm, 2);
64 if (!res) {
65 sq_pop(vm, 1);
66 return false;
67 }
68
69 json.push_back(tmp);
70 }
71 sq_pop(vm, 1);
72 return true;
73 }
74
75 case OT_TABLE: {
76 json = nlohmann::json::object();
77
78 sq_pushnull(vm);
79 while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
80 sq_tostring(vm, -2);
81 std::string_view view;
82 sq_getstring(vm, -1, view);
83 std::string key{view};
84 sq_pop(vm, 1);
85
86 nlohmann::json value;
87 bool res = ScriptAdminMakeJSON(value, vm, -1, depth + 1);
88 sq_pop(vm, 2);

Callers 3

SendMethod · 0.85
TestScriptAdminMakeJSONFunction · 0.85
TestScriptEventAdminPortFunction · 0.85

Calls 9

sq_gettypeFunction · 0.85
sq_getintegerFunction · 0.85
sq_getstringFunction · 0.85
sq_pushnullFunction · 0.85
sq_nextFunction · 0.85
sq_popFunction · 0.85
sq_tostringFunction · 0.85
sq_getboolFunction · 0.85
push_backMethod · 0.80

Tested by 2

TestScriptAdminMakeJSONFunction · 0.68
TestScriptEventAdminPortFunction · 0.68