SpryFox / DarkConfig

DarkConfig is a configuration library for games which supports fast and expressive iteration
Other
150 stars 19 forks source link

Built-in support for reading a differently-named key into a field #26

Closed grahamboree closed 1 year ago

grahamboree commented 2 years ago

This is useful when we want to map a value from a config to a field that has a different name. The usual way this can be accomplished is by writing a FromDoc, but for many cases that's tedious and completely overkill.

For example, given the following class and config

class Player {
  public int currentHealth;
}
# Player.yaml
startingHealth: 100

We want to be able to map the startingHealth value in the yaml to the currentHealth field in a Player instance.

This can currently be accomplished with:

class Player {
  public int currentHealth;
  public static object FromDoc(object existing, DocNode doc) {
    var result = existing as Player ?? new Player();
    result.currentHealth = doc["startingHealth"];
    return result;
  }
}

This has a number of downsides:

An possible solution is to add a ConfigKeyAttribute class that lets the user specify an alternative yaml key to use.

class Player {
  [ConfigKey("startingHealth")]
  public int currentHealth;
}

This also needs to be extended to SetFieldOnObject and SetFieldOnStruct. In these cases it should be implemented as an optional string parameter that lets the user pass the yaml field name through to TypeReifier.