Skip to content

tags: - hello-world - tutorial - getting-started - first-script


Hello World

Let's write your first EverSharp script and run it from C#.


Your First Script

Create a new C# console application and add the following code:

using Elements.Libs.EverSharp;

// Create a runner instance
var runner = new EverSharpRunner();

// Run a simple script
runner.Run("message = \"Hello, EverSharp!\";");

// Check for errors
if (!runner.HasErrors)
{
    // Access the result
    var message = runner.GlobalVariables["message"];
    Console.WriteLine(message);
}

Output:

Hello, EverSharp!

Understanding the Code

1. Create a Runner

var runner = new EverSharpRunner();

The EverSharpRunner is your interface to the EverSharp interpreter. It:

  • Parses EverSharp code
  • Executes scripts
  • Maintains variable state
  • Captures errors

2. Run a Script

runner.Run("message = \"Hello, EverSharp!\";");

The Run method:

  • Takes EverSharp code as a string
  • Parses and executes it
  • Updates the interpreter's variable state
  • Captures any errors

3. Check for Errors

if (!runner.HasErrors)
{
    // Safe to access results
}

Always check HasErrors before accessing results:

  • true if syntax or runtime errors occurred
  • false if execution was successful

4. Access Results

var message = runner.GlobalVariables["message"];

Variables created in scripts are accessible via GlobalVariables:

  • Returns object? type
  • Cast to appropriate C# type when needed
  • Use helper methods for type-safe access (see Using EverSharpRunner)

More Examples

Example 2: Simple Calculation

var runner = new EverSharpRunner();

runner.Run(@"
    a = 10;
    b = 20;
    sum = a + b;
    product = a * b;
");

if (!runner.HasErrors)
{
    var sum = (decimal)runner.GlobalVariables["sum"];
    var product = (decimal)runner.GlobalVariables["product"];

    Console.WriteLine($"Sum: {sum}");        // Sum: 30
    Console.WriteLine($"Product: {product}"); // Product: 200
}

Example 3: Using Functions

var runner = new EverSharpRunner();

runner.Run(@"
    // Define a function
    function greet(name) {
        return ""Hello, "" + name + ""!"";
    }

    // Call the function
    greeting = greet(""World"");
");

if (!runner.HasErrors)
{
    var greeting = (string)runner.GlobalVariables["greeting"];
    Console.WriteLine(greeting); // Hello, World!
}

Example 4: Working with Arrays

var runner = new EverSharpRunner();

runner.Run(@"
    numbers = [1, 2, 3, 4, 5];
    doubled = numbers.Map(x => x * 2);
    total = numbers.ReduceToNum((sum, x) => sum + x, 0);
");

if (!runner.HasErrors)
{
    var doubled = runner.GlobalVariables.GetArray("doubled");
    var total = (decimal)runner.GlobalVariables["total"];

    Console.WriteLine($"Doubled: [{string.Join(", ", doubled)}]"); // [2, 4, 6, 8, 10]
    Console.WriteLine($"Total: {total}");                           // 15
}

Example 5: Date Calculations

var runner = new EverSharpRunner();

runner.Run(@"
    today = $Today();
    nextWeek = $AddDays(today, 7);
    nextYear = $AddYears(today, 1);
");

if (!runner.HasErrors)
{
    var today = (DateTime)runner.GlobalVariables["today"];
    var nextWeek = (DateTime)runner.GlobalVariables["nextWeek"];
    var nextYear = (DateTime)runner.GlobalVariables["nextYear"];

    Console.WriteLine($"Today: {today:yyyy-MM-dd}");
    Console.WriteLine($"Next Week: {nextWeek:yyyy-MM-dd}");
    Console.WriteLine($"Next Year: {nextYear:yyyy-MM-dd}");
}

Multi-Line Scripts

For longer scripts, use verbatim strings (@"..."):

var runner = new EverSharpRunner();

runner.Run(@"
    // Calculate insurance premium
    basePremium = 1000;
    age = 35;

    if (age < 25) {
        premium = basePremium * 1.5;
    } else if (age > 65) {
        premium = basePremium * 1.25;
    } else {
        premium = basePremium;
    }

    discount = 0.10;
    finalPremium = premium * (1 - discount);
");

if (!runner.HasErrors)
{
    var premium = (decimal)runner.GlobalVariables["finalPremium"];
    Console.WriteLine($"Final Premium: ${premium}");
}

Running Expressions

For single expressions, use RunExpression:

var runner = new EverSharpRunner();

// Evaluate an expression
var result = runner.RunExpression("10 + 20 * 3");

if (!runner.HasErrors)
{
    Console.WriteLine($"Result: {result}"); // Result: 70
}

Difference from Run:

  • Run(): Executes statements, returns void, updates variables
  • RunExpression(): Evaluates single expression, returns result directly

Handling Errors

Always handle errors gracefully:

var runner = new EverSharpRunner();

runner.Run(@"
    // This has a syntax error (missing semicolon)
    x = 10
    y = 20;
");

if (runner.HasErrors)
{
    Console.WriteLine("Script errors:");
    foreach (var error in runner.Errors)
    {
        Console.WriteLine($"  - {error}");
    }
}

Output:

Script errors:
  - Expected ';' after expression

Loading Scripts from Files

Read scripts from external files:

using Elements.Libs.EverSharp;

var scriptPath = "scripts/calculate-premium.evs";
var script = File.ReadAllText(scriptPath);

var runner = new EverSharpRunner();
runner.Run(script);

if (!runner.HasErrors)
{
    var result = runner.GlobalVariables["result"];
    Console.WriteLine($"Result: {result}");
}
else
{
    Console.WriteLine("Errors in script:");
    foreach (var error in runner.Errors)
    {
        Console.WriteLine($"  {error}");
    }
}

Best Practices

1. Always Check for Errors

runner.Run(script);

if (runner.HasErrors)
{
    // Handle errors before accessing variables
    LogErrors(runner.Errors);
    return;
}

// Safe to access variables here

2. Use Type-Safe Access

// Avoid
var value = (decimal)runner.GlobalVariables["value"];

// Prefer (with extension methods)
var value = runner.GlobalVariables.GetNumber("value");

3. Validate User Input

// Validate syntax before execution
var errors = runner.Validate(userScript);

if (errors.Any())
{
    Console.WriteLine("Invalid script");
    return;
}

runner.Run(userScript);

4. Reuse Runner Instances

// Create once
var runner = new EverSharpRunner();

// Use multiple times
runner.Run(script1);
ProcessResults(runner.GlobalVariables);

runner.Run(script2);
ProcessResults(runner.GlobalVariables);

Note: Variables persist between runs. Clear state if needed by creating a new instance.


Common Pitfalls

Pitfall 1: Forgetting Semicolons

// ERROR
runner.Run("x = 10");

// CORRECT
runner.Run("x = 10;");

Pitfall 2: Using Single Quotes for Strings

// ERROR
runner.Run("message = 'hello';");

// CORRECT
runner.Run("message = \"hello\";");

Pitfall 3: Accessing Non-Existent Variables

runner.Run("x = 10;");

// ERROR: "y" was never set
var y = runner.GlobalVariables["y"]; // Returns null

Pitfall 4: Type Mismatches

runner.Run("value = \"hello\";");

// ERROR: Cannot cast string to decimal
var num = (decimal)runner.GlobalVariables["value"]; // InvalidCastException

Next Steps

Now that you've run your first EverSharp script:

  1. Learn the API: Using EverSharpRunner
  2. Explore data types: Data Types
  3. See more examples: Examples

Quick Reference

// Create runner
var runner = new EverSharpRunner();

// Run script
runner.Run("x = 10;");

// Run expression
var result = runner.RunExpression("5 + 5");

// Check errors
if (runner.HasErrors)
{
    foreach (var error in runner.Errors)
        Console.WriteLine(error);
}

// Get variables
var x = runner.GlobalVariables["x"];

// Validate syntax
var errors = runner.Validate(script);