Last active
September 26, 2024 08:45
-
-
Save HeathLoganCampbell/e3e3aad27aa6731aff666b6f9ef1c75c to your computer and use it in GitHub Desktop.
Moonsharp timeout after 2 seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace LuaScripts | |
{ | |
using System; | |
using System.Diagnostics; | |
using System.Globalization; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using MoonSharp.Interpreter; | |
public class LuaScriptRunner | |
{ | |
public static void Run() | |
{ | |
Script script = new Script(); | |
int Add(int x, int y) | |
{ | |
Console.WriteLine("Yep, I'm .NET baby!"); | |
return x + y; | |
} | |
string Now() | |
{ | |
return DateTime.Now.ToString(CultureInfo.InvariantCulture); | |
} | |
// Register the method to be callable from Lua | |
script.Globals[nameof(Add)] = (Func<int, int, int>)Add; | |
script.Globals[nameof(Now)] = (Func<string>)Now; | |
// Just stop us being hacked lmao | |
script.Globals["os"] = null; // Disable os library | |
script.Globals["io"] = null; // Disable io library | |
script.Globals["debug"] = null; // Disable debug library | |
script.Globals["package"] = null; // Disable package library | |
string content = @" | |
function long_recursive_function(n) | |
if n <= 0 then | |
return | |
else | |
print(""Finished long recursive process. "", Now()) | |
return long_recursive_function(n - 1) | |
end | |
end | |
long_recursive_function(10000000) | |
"; | |
ExecuteTilTimeout( TimeSpan.FromSeconds(2), () => | |
{ | |
Console.WriteLine("Executing Lua script..."); | |
script.DoString(content); | |
Console.WriteLine("Script executed successfully."); | |
}); | |
Console.WriteLine("Good bye " ); | |
Thread.Sleep(10000); | |
Console.WriteLine("Wild"); | |
} | |
public static void ExecuteTilTimeout(TimeSpan timeSpan, Action action) | |
{ | |
var thread = new Thread(() => action()); | |
thread.Start(); | |
Thread.Sleep(timeSpan); | |
thread.Abort(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment