public static void Write <T>(string field, T value) { readConfigFile(); if (!s_config.ContainsKey(field)) { s_configFields.Add(field); } if (value is bool) { s_config[field] = new ValueAndType( value.ToString().ToLower(), typeof(bool)); } else if (value is int) { s_config[field] = new ValueAndType(value.ToString(), typeof(int)); } else if (value is float) { // Round-trip write for floats. s_config[field] = new ValueAndType( ((float)(object)value).ToString("R"), typeof(int)); } else if (value is string) { s_config[field] = new ValueAndType(value.ToString(), typeof(string)); } else { if (typeof(T).IsPrimitive) { throw new Exception("Cannot write value of type " + typeof(T).ToString() + ". The only supported primitive types in " + "Config are bool, int, and float. (Strings and anything " + "Unity-serializable are fine too.)"); } s_config[field] = new ValueAndType(toJsonViaUtility(value), typeof(string)); } writeConfigFile(); }
private static bool tryConsumeValue(string input, out ValueAndType valueAndType, out string remainingInput) { valueAndType = default(ValueAndType); input = input.TrimStart(); if (input[0] == '"') { // This is a literal string value. var quoteEnd = input.IndexOf('"', 1); if (quoteEnd == -1) { remainingInput = input; return(false); } valueAndType.value = input.Substring(1, quoteEnd - 1); valueAndType.type = typeof(string); remainingInput = input.Substring(quoteEnd + 1); } else if (input[0] == '{') { // This is some more JSON. We don't parse deeper JSON, but we do return // the whole sub-JSON as a string. var jsonEnd = findBalancedClose(input, '{', '}'); valueAndType.value = input.Substring(0, jsonEnd + 1); valueAndType.type = typeof(string); remainingInput = input.Substring(jsonEnd + 1); } else if (input[0] == '[') { // As above. var jsonEnd = findBalancedClose(input, '[', ']'); valueAndType.value = input.Substring(0, jsonEnd + 1); valueAndType.type = typeof(string); remainingInput = input.Substring(jsonEnd + 1); } else { // Three possibilities left: Bool, int, and string. Check here for bool. if (input.Length >= 4 && input.Substring(0, 4).ToLower().Equals("true")) { valueAndType.value = "true"; valueAndType.type = typeof(bool); remainingInput = input.Substring(5); } else if (input.Length >= 5 && input.Substring(0, 5).ToLower().Equals("false")) { valueAndType.value = "false"; valueAndType.type = typeof(bool); remainingInput = input.Substring(6); } else { // Now only float and int are left. Parse to comma or whitespace. var comma = input.IndexOf(','); var whitespace = findWhitespace(input); var earliestCommaOrWhitespace = pickLowestNonNegative(comma, whitespace); if (earliestCommaOrWhitespace == -1) { remainingInput = input; return(false); } valueAndType.value = input.Substring(0, earliestCommaOrWhitespace); valueAndType.type = valueAndType.value.Contains(".") ? typeof(float) : typeof(int); remainingInput = input.Substring(earliestCommaOrWhitespace + 1); } } return(true); }