From 1fe617c349ff09222bca2a7bb4c8edbcf3127062 Mon Sep 17 00:00:00 2001 From: KiritoDev Date: Tue, 1 Jun 2021 16:04:20 -0500 Subject: [PATCH] Added array support on MoonCFG --- src/moon/config/mooncfg.cpp | 8 ++++++-- src/moon/config/mooncfg.h | 9 +++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/moon/config/mooncfg.cpp b/src/moon/config/mooncfg.cpp index 8f9112e6..31f5118d 100644 --- a/src/moon/config/mooncfg.cpp +++ b/src/moon/config/mooncfg.cpp @@ -26,7 +26,7 @@ vector split (const string &s, char delim) { return result; } -string formatNestedKey(string key){ +string MoonCFG::formatNestedKey(string key){ vector dots = split(key, '.'); string tmp; if(dots.size() > 1) @@ -101,7 +101,11 @@ void MoonCFG::setInt(string key, int value){ void MoonCFG::reload(){ if(!fs::exists(this->path) || !fs::is_regular_file(this->path)) return; std::ifstream ifs(this->path); - this->vjson = json::parse(ifs).flatten(); + try{ + this->vjson = json::parse(ifs).flatten(); + } catch(...){ + this->vjson = json::object(); + } } void MoonCFG::save(){ diff --git a/src/moon/config/mooncfg.h b/src/moon/config/mooncfg.h index 860fc2d5..5c4c87a1 100644 --- a/src/moon/config/mooncfg.h +++ b/src/moon/config/mooncfg.h @@ -3,6 +3,7 @@ #include #include +#include #include "moon/libs/nlohmann/json.hpp" class MoonCFG { @@ -13,15 +14,23 @@ public: nlohmann::json vjson; nlohmann::json nested(std::string key); + std::string formatNestedKey(std::string key); std::string getString(std::string key); float getFloat(std::string key); bool getBool(std::string key); int getInt(std::string key); + template< typename T > T* getArray(std::string key) { + return this->nested(key).get>(); + }; void setString(std::string key, std::string value); void setFloat(std::string key, float value); void setBool(std::string key, bool value); void setInt(std::string key, int value); + template< typename T > void setArray(std::string key, std::vector array) { + for(int i = 0; i < array.size(); i++) + this->vjson[formatNestedKey(key)+"/"+std::to_string(i)] = array[i]; + }; void reload(); void save();