Config API
作用
Config API 為原生模組提供類型化 JSON 配置。它可以創建默認配置、把已有用戶
值合併進默認結構、規範化 JSON,並生成啟動器配置編輯器使用的
config.schema.json。
頭文件
C++
#include <pl/Config.hpp>配置類型應是簡單 aggregate struct:字段公開、有默認成員初始化,並帶一個整數
version 字段。
定義配置
C++
#include <pl/Config.hpp>
#include <string>
#include <vector>
enum class Profile {
Quiet,
Balanced,
Verbose,
};
struct HudConfig {
bool showMessage = true;
std::string message = "Hello from config";
double scale = 1.25;
};
struct ModConfig {
int version = 1;
bool enabled = true;
Profile profile = Profile::Balanced;
HudConfig hud;
std::vector<std::string> tags = {"overlay", "example"};
};生成 JSON 的字段順序跟 aggregate 字段順序一致。字段名以 $ 開頭時會被反射忽略。
加載與保存
原生模組生命週期調用期間,ConfigFile 默認可以使用當前模組的
config/config.json 和 config/config.schema.json 路徑。需要非默認位置時仍可
傳入顯式路徑。
C++
class MyMod {
public:
bool load() {
mConfig.emplace();
if (!mConfig->load()) {
getSelf().getLogger().warn("Failed to load config");
return false;
}
return true;
}
bool enable() {
return mConfig && mConfig->value().enabled;
}
[[nodiscard]] ll::mod::NativeMod &getSelf() const;
private:
std::optional<pl::config::ConfigFile<ModConfig>> mConfig;
};運行期修改通過同一個 ConfigFile 保存:
C++
mConfig->value().enabled = false;
mConfig->save();更新行為
ConfigFile<T>::load() 會先從 C++ 默認值開始,再把已有 JSON 合併進去。
- 缺失文件會自動創建。
- 新字段會使用 C++ 默認值補齊。
- 類型可反序列化時保留已有用戶值。
version會強制回到 C++ 默認version。- 文件缺失、損壞或不完整時會規範化並寫回。
- 規範化後不會保留未知 key。
Schema 元數據
schema 生成器能推斷 type、default、嵌套 properties、數組 items 和枚舉選項。
使用 pl::config::Schema<T> 增加 UI 元數據。
C++
template <> struct pl::config::Schema<ModConfig> {
static constexpr std::string_view title = "Example Config";
static constexpr std::string_view description =
"Settings for the example native mod.";
static constexpr FieldSchema field(std::string_view name) {
if (name == "version") {
return {.title = "Version", .readOnly = true};
}
if (name == "enabled") {
return {.title = "Enabled",
.description = "Turns the mod behavior on or off."};
}
if (name == "profile") {
return {.title = "Profile",
.description = "Selects the runtime behavior preset."};
}
return {};
}
};支持的元數據:
| 字段 | Schema 輸出 | 用途 |
|---|---|---|
title | title | 用戶可讀字段名。 |
description | description | 編輯器幫助文本。 |
minimum | minimum | 數值下限。 |
maximum | maximum | 數值上限。 |
readOnly | readOnly | 生成字段或信息字段。 |
支持類型
| C++ 類型 | JSON 表示 |
|---|---|
| aggregate struct | object |
std::string | string |
bool | boolean |
| integral types | integer |
| floating point types | number |
| enum | magic_enum 能命名時為 string enum |
std::vector<T> | array |
std::optional<T> | value 或 null |
配置對象保持簡單。避免自定義構造、私有字段和帶複雜邏輯的配置類型。