Added array support on MoonCFG

This commit is contained in:
KiritoDev 2021-06-01 16:04:20 -05:00
parent e3b90fcea1
commit 1fe617c349
2 changed files with 15 additions and 2 deletions

View File

@ -26,7 +26,7 @@ vector<string> split (const string &s, char delim) {
return result; return result;
} }
string formatNestedKey(string key){ string MoonCFG::formatNestedKey(string key){
vector<string> dots = split(key, '.'); vector<string> dots = split(key, '.');
string tmp; string tmp;
if(dots.size() > 1) if(dots.size() > 1)
@ -101,7 +101,11 @@ void MoonCFG::setInt(string key, int value){
void MoonCFG::reload(){ void MoonCFG::reload(){
if(!fs::exists(this->path) || !fs::is_regular_file(this->path)) return; if(!fs::exists(this->path) || !fs::is_regular_file(this->path)) return;
std::ifstream ifs(this->path); std::ifstream ifs(this->path);
try{
this->vjson = json::parse(ifs).flatten(); this->vjson = json::parse(ifs).flatten();
} catch(...){
this->vjson = json::object();
}
} }
void MoonCFG::save(){ void MoonCFG::save(){

View File

@ -3,6 +3,7 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include <sstream>
#include "moon/libs/nlohmann/json.hpp" #include "moon/libs/nlohmann/json.hpp"
class MoonCFG { class MoonCFG {
@ -13,15 +14,23 @@ public:
nlohmann::json vjson; nlohmann::json vjson;
nlohmann::json nested(std::string key); nlohmann::json nested(std::string key);
std::string formatNestedKey(std::string key);
std::string getString(std::string key); std::string getString(std::string key);
float getFloat(std::string key); float getFloat(std::string key);
bool getBool(std::string key); bool getBool(std::string key);
int getInt(std::string key); int getInt(std::string key);
template< typename T > T* getArray(std::string key) {
return this->nested(key).get<std::vector<T>>();
};
void setString(std::string key, std::string value); void setString(std::string key, std::string value);
void setFloat(std::string key, float value); void setFloat(std::string key, float value);
void setBool(std::string key, bool value); void setBool(std::string key, bool value);
void setInt(std::string key, int value); void setInt(std::string key, int value);
template< typename T > void setArray(std::string key, std::vector<T> array) {
for(int i = 0; i < array.size(); i++)
this->vjson[formatNestedKey(key)+"/"+std::to_string(i)] = array[i];
};
void reload(); void reload();
void save(); void save();