Retrieve modified variable value
-
12-06-2021 - |
Pregunta
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?
Solución
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;
Otros consejos
Setvariable is to change inputs
e.g.
if you had y = y + 1
Before the DLR you would have made your script 'y = 11' followed by 'y = y + 1' and if you then wanted to run it again for y = 15, you would have built a new script initialising y to 15 and then it would have been interpreted again.
What's happening is y = 33 is getting replaced by y = 11, setvariable is so you can use the same compiled script for different inputs