Last active
September 1, 2018 13:48
-
-
Save xanathar/6b636f62b5e4b7d4b893b31a8bd950c3 to your computer and use it in GitHub Desktop.
Protect globals in C# using MoonSharp
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
using MoonSharp.Interpreter; | |
using System; | |
namespace Test | |
{ | |
class Program | |
{ | |
private static void CaptureNewIndex(Table table, DynValue index, DynValue value) | |
{ | |
if (index.String == "math") | |
{ | |
return; // could do a throw new ScriptRuntimeException($"{index} is read-only"); | |
} | |
table.Set(index, value); | |
} | |
static void Main(string[] args) | |
{ | |
string scriptCode = @" | |
math = { sin = function(x) return 3*x; end } | |
print(math.sin(1.57)); | |
"; | |
Script script = new Script(CoreModules.Preset_HardSandbox); | |
Table protectedTable = new Table(script); | |
protectedTable.MetaTable = new Table(script); | |
protectedTable.MetaTable["__index"] = script.Globals; | |
protectedTable.MetaTable["__newindex"] = (Action<Table, DynValue, DynValue>)CaptureNewIndex; | |
script.DoString(scriptCode, protectedTable); | |
Console.WriteLine(">> done"); | |
Console.ReadKey(); | |
} | |
} | |
} |
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
using MoonSharp.Interpreter; | |
using System; | |
namespace Test | |
{ | |
class Program | |
{ | |
private static void CaptureNewIndex(Table table, DynValue index, DynValue value) | |
{ | |
if (index.String == "math") | |
{ | |
return; // could do a throw new ScriptRuntimeException($"{index} is read-only"); | |
} | |
table.Set(index, value); | |
} | |
static void Main(string[] args) | |
{ | |
string scriptCode = @" | |
math = { sin = function(x) return 3*x; end } | |
print(math.sin(1.57)); | |
"; | |
Script script = new Script(CoreModules.None); | |
Table protectedTable = new Table(script); | |
protectedTable.RegisterCoreModules(CoreModules.Preset_HardSandbox); | |
script.Globals.MetaTable = new Table(script); | |
script.Globals.MetaTable["__index"] = protectedTable; | |
script.Globals.MetaTable["__newindex"] = (Action<Table, DynValue, DynValue>)CaptureNewIndex; | |
script.DoString(scriptCode); | |
Console.WriteLine(">> done"); | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment