summaryrefslogtreecommitdiffstats
path: root/DTFormatN.c
blob: 6c0190166cf21ad937175c79d0e1cc004bbd0570 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#strict 2

// FormatN("%identifier%format specification%...", { identifier = "content", ... });
// example: FormatN("%foo%s% %bar%s%", { foo = "Hello", bar = "World" }) = "Hello World"
global func FormatN(string format, map items)
{
	var ret = "";

	var inPlaceholder = 0;
	var placeholderType = "%";
	var placeholderPart = "";

	for(var i = 0; i < GetLength(format); ++i)
	{
		var c = format[i];
		if(c == "%")
		{
			if(inPlaceholder == 0)
			{
				inPlaceholder = 1;
			}
			else if(inPlaceholder == 1)
			{
				if(placeholderPart == "")
				{
					ret ..= "%";
					inPlaceholder = 0;
				}
				else
				{
					inPlaceholder = 2;
				}
			}
			else if(inPlaceholder == 2)
			{
				ret ..= Format(placeholderType, items[placeholderPart]);

				inPlaceholder = 0;
				placeholderType = "%";
				placeholderPart = "";
			}
		}
		else
		{
			if(inPlaceholder == 0)
			{
				ret ..= c;
			}
			else if(inPlaceholder == 1)
			{
				placeholderPart ..= c;
			}
			else if(inPlaceholder == 2)
			{
				placeholderType ..= c;
			}
		}
	}

	if(inPlaceholder == 1)
	{
		FatalError(Format("FormatN: Placeholder not finished at end of format-string: \"%%%s\"", placeholderPart));
		return 0;
	}
	else if(inPlaceholder == 2)
	{
		FatalError(Format("FormatN: Placeholder not finished at end of format-string: \"%%%s%s\"", placeholderPart, placeholderType));
		return 0;
	}

	return ret;
}