oleg-shilo / cs-script

C# scripting platform
http://www.cs-script.net
MIT License
1.62k stars 235 forks source link

How to use variables between host and script #308

Closed Gomez12 closed 2 years ago

Gomez12 commented 2 years ago

Hello,

What I want to do is offer up some way to have some data in the host transferred to the script and back. Is there any way this is possible.

So for example what I want to do is for example (I don't need a dictionary, I basically need a way to get data In and out):

var inputVariables  = new Dictionary<string,string>();
inputVariables.Add("inputFile","c:\pagefile.sys");

var outputVariables  = new Dictionary<string,string>();

dynamic script = new_evaluator.LoadCode($@"
                                           using System;
                                           public class Script
                                           {{
                                               public int Sum(int a, int b) => {
var x = getinputVariable("inputFile");
setoutputVariable("outputFile","c:\windows\" + Path.getFileName(x));
return a + b;
}
                                           }}");

var result = script.Sum(7, 3);
foreach (var x in outputVariables)
{
...
And here I work with the outputFile variable...
}

` I know I can achieve this by changing the public int Sum and add some variables there, but I want to use this without changing a lot of scripts.

Is this possible?

oleg-shilo commented 2 years ago

I am not sure I like your API design :)

But of course, you can make your outputVariables into a public static object and access it from the script:



public class Runtime
{
    public static Dictionary<string,string> OutputVariables  = new Dictionary<string,string>();
}

. . .

LoadCode(@"using System;
           public class Script
           {
               public int Sum(int a, int b)  
               {
                   Runtime.OutputVariables[""test_key""]=""test_value"";
                   . . .
Gomez12 commented 2 years ago

We had a very nicely designed scripting pipeline where multiple people could insert many scripts in various scripting languages and the pipeline would run because everything was defined as 1 or more inputs, 1 output.

But now some people have the need to get stuff not from input, but from somewhere random in the pipeline where it is not the return value And because we support multiple scripting engines we need to have it as part of the pipeline so that cs-script can set a variable and a Lua-script can get the value.

Your static implementation is not by far the worst implementation :)