Skip to content

Commit 6258bf0

Browse files
committed
LuaUtility.cs
~ Move Regex for format parts to a GeneratedRegex function to improve performance. ~ Only read the LuaVM template once, as it is read from the resources on every subsequent use. ~ Account for the absence of the LuaVM in results.
1 parent d09e77b commit 6258bf0

File tree

1 file changed

+28
-15
lines changed

1 file changed

+28
-15
lines changed

services/grid-bot/lib/utility/Implementation/LuaUtility.cs

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,40 +14,53 @@
1414
/// <summary>
1515
/// Utility for interacting with grid-server Lua.
1616
/// </summary>
17-
public class LuaUtility : ILuaUtility
17+
public partial class LuaUtility : ILuaUtility
1818
{
1919
private static readonly Assembly _assembly = Assembly.GetExecutingAssembly();
2020
private const string _luaVmResource = "Grid.Bot.Lua.LuaVMTemplate.lua";
2121

22-
private static string FixFormatString(string input)
22+
[GeneratedRegex(@"{{(\d{1,2})}}", RegexOptions.IgnoreCase | RegexOptions.Compiled)]
23+
private static partial Regex FormatPartRegex();
24+
25+
26+
private static readonly string _LuaVM;
27+
28+
static LuaUtility()
2329
{
24-
//language=regex
25-
const string partRegex = @"{{(\d{1,2})}}";
30+
using var stream = _assembly.GetManifestResourceStream(_luaVmResource);
31+
using var reader = new StreamReader(stream);
2632

33+
_LuaVM = FixFormatString(reader.ReadToEnd());
34+
}
35+
36+
private static string FixFormatString(string input)
37+
{
2738
input = input.Replace("{", "{{");
2839
input = input.Replace("}", "}}");
2940

30-
input = Regex.Replace(input, partRegex, (m) => { return $"{{{m.Groups[1]}}}"; });
41+
input = FormatPartRegex().Replace(input, (m) => { return $"{{{m.Groups[1]}}}"; });
3142

3243
return input;
3344
}
3445

3546
/// <inheritdoc cref="ILuaUtility.LuaVMTemplate"/>
36-
public string LuaVMTemplate
37-
{
38-
get {
39-
using var stream = _assembly.GetManifestResourceStream(_luaVmResource);
40-
using var reader = new StreamReader(stream);
41-
42-
return FixFormatString(reader.ReadToEnd());
43-
}
44-
}
47+
public string LuaVMTemplate => _LuaVM;
4548

4649
/// <inheritdoc cref="ILuaUtility.ParseResult(IEnumerable{LuaValue})"/>
4750
public (string result, ReturnMetadata metadata) ParseResult(IEnumerable<LuaValue> result)
4851
{
52+
if (result.Count() == 1)
53+
{
54+
// Legacy case, where LuaVM is not enabled.
55+
56+
var mockMetadata = new ReturnMetadata();
57+
mockMetadata.Success = true;
58+
59+
return ((string)Lua.ConvertLua(result.First()), mockMetadata);
60+
}
61+
4962
return (
50-
(string)Lua.ConvertLua(result.FirstOrDefault()),
63+
(string)Lua.ConvertLua(result.FirstOrDefault()),
5164
JsonConvert.DeserializeObject<ReturnMetadata>((string)Lua.ConvertLua(result.ElementAtOrDefault(1)))
5265
);
5366
}

0 commit comments

Comments
 (0)