Search code examples
c#ironrubydynamic-language-runtime

Retrieve modified variable value


I have an IronRuby script that modifies the value of a variable set via the ScriptScope.

I'd like to retrieve the value of the variable after it's been modified, but I get the old value.

This is the code I have:

var engine = Ruby.CreateEngine();
var scope = engine.Runtime.CreateScope();

scope.SetVariable("y", 11);

var source = engine.CreateScriptSourceFromString("y=33; puts y;", SourceCodeKind.Statements);
source.Execute(scope);

The above code executes and outputs 33 to the console, which is OK.

However, I tried adding the following line after the above code:

Console.WriteLine(scope.GetVariable("y"));

and it outputs 11, which is the original value.

Is there a way to get the new variable value?


Solution

  • With IronPython, to retrieve a value, I use a proxy object like this.

    public class ScriptProxy
    {
        private int _result;
    
        public int Result
        {
            get { return this._result; }
            set { this._result = value; }
        }
    }
    

    And I call SetVariable to pass an instance of the ScriptObject :

    ScriptEngine pyEngine = Python.CreateEngine();
    ScriptScope pyScope = pyEngine.CreateScope();
    
    ScriptProxy proxy = new ScriptProxy();
    pyScope.SetVariable("proxy", proxy);
    

    In your script you can set the result :

    proxy.Result=33;