Skip to content

Instantly share code, notes, and snippets.

@xanathar
Created April 13, 2015 08:36
Show Gist options
  • Save xanathar/2c777a79937398834ad4 to your computer and use it in GitHub Desktop.
Save xanathar/2c777a79937398834ad4 to your computer and use it in GitHub Desktop.
[MoonSharp] - How to limit execution of a script to n instructions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
namespace Tutorials.Chapters
{
static class X1
{
public class MyException : Exception
{
}
class BreakAfterManyInstructionsDebugger : IDebugger
{
int m_InstructionCounter = 0;
List<DynamicExpression> m_Dynamics = new List<DynamicExpression>();
public void SetSourceCode(SourceCode sourceCode)
{
}
public void SetByteCode(string[] byteCode)
{
}
public bool IsPauseRequested()
{
return true;
}
public bool SignalRuntimeException(ScriptRuntimeException ex)
{
return false;
}
public DebuggerAction GetAction(int ip, SourceRef sourceref)
{
m_InstructionCounter += 1;
if ((m_InstructionCounter % 1000) == 0)
Console.Write(".");
if (m_InstructionCounter > 50000)
throw new MyException();
return new DebuggerAction()
{
Action = DebuggerAction.ActionType.StepIn,
};
}
public void SignalExecutionEnded()
{
}
public void Update(WatchType watchType, IEnumerable<WatchItem> items)
{
}
public List<DynamicExpression> GetWatchItems()
{
return m_Dynamics;
}
public void RefreshBreakpoints(IEnumerable<SourceRef> refs)
{
}
}
static void ChangePlatform()
{
Script script = new Script();
try
{
script.AttachDebugger(new BreakAfterManyInstructionsDebugger());
script.DoString(@"
x = 0;
while true do x = x + 1; end;
");
}
catch (MyException)
{
Console.WriteLine("Done. x = {0}", script.Globals["x"]);
}
}
}
}
@Bibli2311
Copy link

Could you add a licence to this code snippet?

@xanathar
Copy link
Author

xanathar commented May 1, 2021

Consider this in Public Domain (i.e. I waive the copyrights on the above, do what you want with it).

@Bibli2311
Copy link

Thanks for making this code in the public domain. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment