space_engineers/Mixins/ConfigParser/ConfigParser.cs

47 lines
1.4 KiB
C#

using Sandbox.ModAPI.Ingame;
using System;
using System.Collections.Generic;
namespace IngameScript
{
partial class Program
{
public class ConfigParser
{
private Dictionary<string, string> _config;
private IMyTerminalBlock _input;
public ConfigParser(IMyTerminalBlock input)
{
_input = input;
_config = new Dictionary<string, string>();
Parse();
}
// Get a config value, or a default value.
// that also does type inference, but the type of `defaultValue` must contain a `Parse()` method.
public T GetValue<T>(string key, T defaultValue)
{
if (!_config.ContainsKey(key))
{
return defaultValue;
}
return (T)Convert.ChangeType(_config[key], typeof(T));
}
// Only call this method manually if you are monitoring CustomData for changes.
public void Parse()
{
_config.Clear();
string[] lines = _input.CustomData.Split('\n');
foreach (string line in lines)
{
string[] tokens = line.Split('=');
if (tokens.Length != 2) continue;
_config[tokens[0]] = tokens[1];
}
}
}
}
}