Skip to content

Commit

Permalink
LuaUtility.cs
Browse files Browse the repository at this point in the history
~ 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.
  • Loading branch information
jf-06 committed Sep 17, 2024
1 parent d09e77b commit 6258bf0
Showing 1 changed file with 28 additions and 15 deletions.
43 changes: 28 additions & 15 deletions services/grid-bot/lib/utility/Implementation/LuaUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,40 +14,53 @@
/// <summary>
/// Utility for interacting with grid-server Lua.
/// </summary>
public class LuaUtility : ILuaUtility
public partial class LuaUtility : ILuaUtility
{
private static readonly Assembly _assembly = Assembly.GetExecutingAssembly();
private const string _luaVmResource = "Grid.Bot.Lua.LuaVMTemplate.lua";

private static string FixFormatString(string input)
[GeneratedRegex(@"{{(\d{1,2})}}", RegexOptions.IgnoreCase | RegexOptions.Compiled)]
private static partial Regex FormatPartRegex();


private static readonly string _LuaVM;

static LuaUtility()
{
//language=regex
const string partRegex = @"{{(\d{1,2})}}";
using var stream = _assembly.GetManifestResourceStream(_luaVmResource);
using var reader = new StreamReader(stream);

_LuaVM = FixFormatString(reader.ReadToEnd());
}

private static string FixFormatString(string input)
{
input = input.Replace("{", "{{");
input = input.Replace("}", "}}");

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

return input;
}

/// <inheritdoc cref="ILuaUtility.LuaVMTemplate"/>
public string LuaVMTemplate
{
get {
using var stream = _assembly.GetManifestResourceStream(_luaVmResource);
using var reader = new StreamReader(stream);

return FixFormatString(reader.ReadToEnd());
}
}
public string LuaVMTemplate => _LuaVM;

/// <inheritdoc cref="ILuaUtility.ParseResult(IEnumerable{LuaValue})"/>
public (string result, ReturnMetadata metadata) ParseResult(IEnumerable<LuaValue> result)
{
if (result.Count() == 1)
{
// Legacy case, where LuaVM is not enabled.

var mockMetadata = new ReturnMetadata();
mockMetadata.Success = true;

return ((string)Lua.ConvertLua(result.First()), mockMetadata);
}

return (
(string)Lua.ConvertLua(result.FirstOrDefault()),
(string)Lua.ConvertLua(result.FirstOrDefault()),
JsonConvert.DeserializeObject<ReturnMetadata>((string)Lua.ConvertLua(result.ElementAtOrDefault(1)))
);
}
Expand Down

0 comments on commit 6258bf0

Please sign in to comment.