2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file script_admin.cpp Implementation of ScriptAdmin. */
10 #include "../../stdafx.h"
11 #include "script_admin.hpp"
12 #include "script_log.hpp"
13 #include "../../network/network_admin.h"
14 #include "../script_instance.hpp"
15 #include "../../string_func.h"
16 #include "../../3rdparty/nlohmann/json.hpp"
18 #include "../../safeguards.h"
21 * Convert a Squirrel structure into a JSON object.
23 * This function is not "static", so it can be tested in unittests.
25 * @param json The resulting JSON object.
26 * @param vm The VM to operate on.
27 * @param index The index we are currently working for.
28 * @param depth The current depth in the squirrel struct.
29 * @return True iff the conversion was successful.
31 bool ScriptAdminMakeJSON(nlohmann::json
&json
, HSQUIRRELVM vm
, SQInteger index
, int depth
= 0)
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
38 switch (sq_gettype(vm
, index
)) {
41 sq_getinteger(vm
, index
, &res
);
49 sq_getstring(vm
, index
, &buf
);
51 json
= std::string(buf
);
56 json
= nlohmann::json::array();
59 while (SQ_SUCCEEDED(sq_next(vm
, index
- 1))) {
62 bool res
= ScriptAdminMakeJSON(tmp
, vm
, -1, depth
+ 1);
76 json
= nlohmann::json::object();
79 while (SQ_SUCCEEDED(sq_next(vm
, index
- 1))) {
80 /* Squirrel ensure the key is a string. */
81 assert(sq_gettype(vm
, -2) == OT_STRING
);
83 sq_getstring(vm
, -2, &buf
);
84 std::string key
= std::string(buf
);
87 bool res
= ScriptAdminMakeJSON(value
, vm
, -1, depth
+ 1);
102 sq_getbool(vm
, index
, &res
);
104 json
= res
? true : false;
114 ScriptLog::Error("You tried to send an unsupported type. No data sent.");
119 /* static */ SQInteger
ScriptAdmin::Send(HSQUIRRELVM vm
)
121 if (sq_gettop(vm
) - 1 != 1) return sq_throwerror(vm
, "wrong number of parameters");
123 if (sq_gettype(vm
, 2) != OT_TABLE
) {
124 return sq_throwerror(vm
, "ScriptAdmin::Send requires a table as first parameter. No data sent.");
128 if (!ScriptAdminMakeJSON(json
, vm
, -1)) {
129 sq_pushinteger(vm
, 0);
133 NetworkAdminGameScript(json
.dump());
135 sq_pushinteger(vm
, 1);