* 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. */
| 29 | * @return True iff the conversion was successful. |
| 30 | */ |
| 31 | bool 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); |