Here’s a complete example that calculates a factorial using Lua:
using SolarSharp.Interpreter;using SolarSharp.Interpreter.DataTypes;double Factorial(){ string script = @" -- defines a factorial function function fact (n) if (n == 0) then return 1 else return n*fact(n - 1) end end return fact(5)"; LuaValue res = Script.RunString(script); return res.Number;}
That’s it! With just a few lines of code, you’ve executed Lua code and retrieved the result.
The Script.RunString() method is the quickest way to run Lua code. It creates a new Script instance, executes the code, and returns the result.
The Script class is the core of SolarSharp. It represents a Lua scripting session:
using SolarSharp.Interpreter;// Create a new script instanceScript script = new Script();// Load and execute Lua codeLuaValue result = script.DoString("return 2 + 2");Console.WriteLine(result.Number); // Output: 4
Script script = new Script();// Set a global variablescript.Globals["myVar"] = 10;// Access it in scriptsLuaValue result = script.DoString("return myVar * 2");Console.WriteLine(result.Number); // 20
Lua tables are the primary data structure. Here’s how to work with them:
Script script = new Script();// Create and populate a Lua tablestring luaCode = @" return { name = 'SolarSharp', version = '2.0.0', features = {'Fast', 'Easy', 'Powerful'} }";LuaValue result = script.DoString(luaCode);Table table = result.Table;// Access table valuesConsole.WriteLine(table["name"].String); // SolarSharpConsole.WriteLine(table["version"].String); // 2.0.0// Access array elements (Lua arrays are 1-indexed)Table features = table["features"].Table;Console.WriteLine(features[1].String); // Fast
Here’s a complete console application that demonstrates various SolarSharp features:
using System;using SolarSharp.Interpreter;using SolarSharp.Interpreter.DataTypes;using SolarSharp.Interpreter.Errors;class Program{ static void Main() { // Create a script instance Script script = new Script(); // Define a Lua function script.DoString(@" function calculate(x, y, operation) if operation == 'add' then return x + y elseif operation == 'multiply' then return x * y elseif operation == 'power' then return x ^ y else return nil end end "); // Get the function LuaValue calcFunc = script.Globals["calculate"]; // Call it with different operations var sum = script.Call(calcFunc, 5, 3, "add"); var product = script.Call(calcFunc, 5, 3, "multiply"); var power = script.Call(calcFunc, 5, 3, "power"); Console.WriteLine($"5 + 3 = {sum.Number}"); // 8 Console.WriteLine($"5 * 3 = {product.Number}"); // 15 Console.WriteLine($"5 ^ 3 = {power.Number}"); // 125 }}
Check out the API Reference for complete documentation on all available methods and properties.