feat(loading): robust error reporting and mutation
cfg now reports which fields are missing when loading. Further, the mutate method has been added for easier mutation of the underlying configuration struct
This commit is contained in:
28
readme.md
28
readme.md
@@ -33,10 +33,12 @@ and strongly typed.
|
||||
#include "fourdst/config/config.h"
|
||||
#include <string>
|
||||
#include <print>
|
||||
#include <optional>
|
||||
|
||||
struct MyPhysicsOptions {
|
||||
int gravity = 10;
|
||||
float friction = 0.5f;
|
||||
std::optional<float> dampening = 0.1f;
|
||||
bool enable_wind = false;
|
||||
};
|
||||
|
||||
@@ -64,12 +66,38 @@ int main() {
|
||||
// You can load a config from a file
|
||||
try {
|
||||
cfg.load("my_config.toml");
|
||||
// You can also pass an optional bool as a second argument to turn on verbose error
|
||||
// reporting. This will display a tree of missing or invalid fields. Note that due to limitations
|
||||
// in C++'s ability to detect default iniailized values vs initializer list values
|
||||
// missing fields which you set an initializer list for are still considered missing.
|
||||
// **ONLY fields marked with std::optional are exempt from this rule.**
|
||||
} catch (const fourdst::config::exceptions::ConfigError& e) {
|
||||
std::println("Error loading config: {}", e.what());
|
||||
}
|
||||
|
||||
// You can access the config values
|
||||
std::println("My Simulation Name: {}, My Simulation Gravity: {}", cfg->name, cfg->physics.gravity);
|
||||
|
||||
// libconfig intentioanlly discourages direct modification of config values. However, if you need
|
||||
// to modify values after loading them you can use the mutate function. This takes a lambda
|
||||
// which recives a mutable reference to the underlying config struct.
|
||||
|
||||
cfg.mutate([](MySimulationConfig& config) {
|
||||
config->physics.enable_wind = true;
|
||||
});
|
||||
|
||||
// Making these mutations will put the config into a "MODIFIED" state and will cache the unmodified values.
|
||||
// You can reset the state and revert to the unmodified values with the reset function.
|
||||
|
||||
cfg.reset();
|
||||
|
||||
// The current state of the config can be checked with the get_state() function or the describe_state() function.
|
||||
// get_state returns an enum value while describe_state returns a human readable string.
|
||||
|
||||
std::println("Config State: {}", cfg.describe_state());
|
||||
fourdst::config::ConfigState state = cfg.get_state();
|
||||
|
||||
// Possible states are DEFAULT, LOADED_FROM_FILE, and MODIFIED
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Reference in New Issue
Block a user