Skip to content

Working with a Context

Kameron Brooks edited this page Dec 26, 2018 · 8 revisions

Working with a Context

What is a context?

The context is interface between your application and your run-time script. The context provides the functionality that you want your scripts to be able to have. It is basically an object that has properties and methods that you want to leverage in your script. The context object's properties and methods are accessed as part of the global scope alongside global variables that your script declares. The context is passed in at execution time and the script operates on it.

CCL is pretty useless without a context. CCL is designed to not really be able to do much without a context to operate on. What your script can do really is defined by what context it is operating on. This principal provides flexibility and security.

Flexibility

CCL can do what ever you want it to do based on the context you pass in.

Security

CCL can only do what you want it to do based on the context you pass in.

The very nature of CCL is dangerous because your application is running code that is passed in from elsewhere. The code is untrusted and could be malicious. Since that could be the case, you can limit the amount of influence that a ccl script has by only exposing functions and properties in your application that you feel are safe.


How to Pass a Context to CCL?

First, create a new class:

class MyContext {
   int _member1;               // private member variable
   public int member1 {        // public property
      get {
         return _member1;
      }
      set {
         _member1 = value;
      }
   }
   public string PrintData() {  // public method
      return member1.ToString();
   }
}

Compile the script, pass in the context, and call the compiled function

Compiler compiler = new Compiler(tokens);
CompiledScript compiledScript = compiler.compile();

// Create a new instance of your custom context object
MyContext context = new MyContext();

// Pass it in to the script with the SetContext method
compiledScript.SetContext(context);

// Call the compiled function
compiledScript.function();

How to Pass Data into a Script?

You can pass variable values in to the script by using the SetVariable method of the CompiledScript class. This is useful for passing data directly in from the application to the script as a global variable. For this to work, a global variable must exist in the script with the specified identifier.

// set the global variable v to 100
compiledScript.SetVariable("v", 100);

// set the global variable col to a new Color object
compiledScript.SetVariable("col", new Color(1,1,1));

// set the global variable func to a new delegate
compiledScript.SetVariable("func" , (Func<object>)(() => { return "lambda"; }));

``

- - -