chaosbot/ChaosBot/Services/ProgrammingLanguageInterpreter/LuaProgrammingLanguageInterpreter.cs
2020-09-26 18:27:24 +02:00

54 lines
1.5 KiB
C#

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Discord.Commands;
using Neo.IronLua;
using NLog;
namespace ChaosBot.Services.ProgrammingLanguageInterpreter
{
internal class LuaProgrammingLanguageInterpreter : IProgrammingLanguageInterpreter
{
private static readonly ILogger Logger = Program.GetLogger();
private readonly StringBuilder _outputBuilder = new StringBuilder();
private Lua _lua;
public string Interpret(SocketCommandContext context, string content, string command)
{
using (_lua = new Lua())
{
// This needs to be dynamic if we want to call
// functions from within the lua environment
// This is a runtime type check
dynamic env = _lua.CreateEnvironment();
ParamsDelegate printDel = Print;
env.print = printDel;
env.context = context;
string code = content;
env.dochunk(code, $"{command}.lua");
return _outputBuilder.ToString();
}
}
public void StopExecution()
{
_lua.Dispose();
}
private delegate void ParamsDelegate(params object[] parameters);
private void Print(params object[] parameters)
{
string str = string.Join(" ", from param in parameters select param == null ? string.Empty : param.ToString());
_outputBuilder.Append(str);
}
}
}