Поделиться через


Quick notes on ScriptScope

ScriptScope

is one of the key types available in the DLR Hosting API. They act as a context in which hosts execute code and record the effects of execution like changes in object values, creation of new objects etc.

Prior to any code execution, ScriptScopes can be populated with variables by hosts using methods defined in this type and these variables are then available to any code that’s executed in its context. ScriptScope also acts as a unit of isolation - it maintains state, isolates side effects from code and can be reused as a context to execute another code snippet.

The Hosting API spec describes this type in detail. The following list is a short summary of some of the key points described by the spec

  • This class represents a namespace essentially. Hosts can bind variable names in ScriptScopes, fetch variable values, etc. Hosts can execute code within scopes for distinct name bindings.
  • You create instances of ScriptScopes using the CreateScope and ExecuteFile methods on ScriptRuntime or CreateScope on ScriptEngine.

o ScriptScope scope = pythonEngine.CreateScope();

o ScriptScope scope = runtime.CreateScope();

o ScriptScope scope = runtime.ExecuteFile(@"C:\Foo.py");

  • If a ScriptScope were created with a default language, then members such as Execute and IncludeFile use that language's engine to perform these operations. If the ScriptScope has no default language, then these convenience methods throw an exception, and the Engine property returns null.
  • At runtime, the DLR manifests a ScriptScope object as a dynamic object. This means that normal object member access sees the variables stored in the scope, not the members of the static .NET ScriptScope type.
  • Hosts can use ScriptScopes to execute any kind of code within their namespace context. This method offers an easy and convenient way to execute a piece of script code and get a result from the execution. The variables from the execution are also bound to this ScriptScope and this lets hosts examine the state after code execution

         o public object Execute(string code)

  • ScriptScopes has members to support operations on variables like set, edit, remove, clear etc.

o public bool ContainsVariable(string name)

o public object GetVariable(string name)

o public void SetVariable(string name, object value)

o public bool RemoveVariable(string name)

o public void ClearVariables()

In addition to the above items, the spec also contains details about each of the method defined in this type and their arguments.

Comments