SolarSharp provides several methods to load and execute Lua scripts. You can execute code from strings, files, or streams, and optionally provide custom global contexts.
using SolarSharp.Interpreter;// Execute a script and get the resultvar result = Script.RunString("return 2 + 2");Console.WriteLine(result.Number); // 4
Script script = new Script();// Execute a script fileLuaValue result = script.DoFile("scripts/main.lua");// With custom globalsTable globals = new Table(script);globals["config"] = myConfigObject;LuaValue result2 = script.DoFile("scripts/init.lua", globals);
// Creates a new Script instance and executes the codeLuaValue result = Script.RunString("return math.sqrt(16)");Console.WriteLine(result.Number); // 4
// Creates a new Script instance and executes the fileLuaValue result = Script.RunFile("script.lua");
These static methods create a new Script instance for each call. For better performance when executing multiple scripts, create a single Script instance and reuse it.
You can separate loading from execution using LoadString, LoadFile, and LoadFunction:
Script script = new Script();// Load (compile) the script without executingLuaValue function = script.LoadString("return x + y");// Execute multiple times with different globalsTable globals1 = new Table(script);globals1["x"] = 10;globals1["y"] = 5;LuaValue result1 = script.Call(function); // Uses Script.GlobalsTable globals2 = new Table(script);globals2["x"] = 20;globals2["y"] = 3;// To use different globals, you need to load the function with that tableLuaValue function2 = script.LoadString("return x + y", globals2);LuaValue result2 = script.Call(function2); // 23
You can create isolated execution environments with custom global tables:
Script script = new Script();// Create a sandboxed environmentTable sandbox = new Table(script);sandbox["print"] = script.Globals["print"]; // Allow print onlysandbox["math"] = script.Globals["math"]; // Allow math library// This will workscript.DoString("print(math.sqrt(16))", sandbox);// This will fail - 'io' is not available in sandbox// script.DoString("io.open('file.txt')", sandbox);
When creating a Script, you can specify which core modules to load:
using SolarSharp.Interpreter.Modules;// Default preset (most common modules)Script script1 = new Script();// Specific modulesScript script2 = new Script(CoreModules.Basic | CoreModules.Table | CoreModules.String);// All modulesScript script3 = new Script(CoreModules.Preset_Complete);// Minimal (no standard libraries)Script script4 = new Script(CoreModules.None);