C# and CS-Script: variables not in context

298 Views Asked by At

[C# newbie]

Hi. This is a test of CS-Script 3.28.7, to add scripting to C#. I need to implement very simple functions that will be later read from a cfg file.

I went through the docs, but didn't find the way to read external classes and static vars. I get for both values and rnd the message the name XXX is not available in this context.

What am I forgetting?

using System;
using CSScriptLibrary;

namespace EmbedCS
{
    class Program
    {
        public static int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        static Random rnd = new Random();

        static void Main(string[] args)
        {
            ExecuteTest();
            Console.Read();
        }

        private static void ExecuteTest()
        {
            bool result;
            var scriptFunction = CSScript.CreateFunc<bool>(@"
                bool func() {
                    int a = rnd.Next(10);
                    int b = rnd.Next(10);
                    return values[a] > values[b];
                }
            ");

            result = (bool)scriptFunction();
            Console.Read();
        }
    }
}
1

There are 1 best solutions below

2
mharti On BEST ANSWER

This one should work

using System;
using CSScriptLibrary;

namespace EmbedCS
{
    public class Program
    {
        public static int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        public static Random rnd = new Random();

        static void Main(string[] args)
        {
            ExecuteTest();
            Console.Read();
        }

        private static void ExecuteTest()
        {
            bool result;
            var scriptFunction = CSScript.CreateFunc<bool>(@"
                bool func() {
                    int a = EmbedCS.Program.rnd.Next(10);
                    int b = EmbedCS.Program.rnd.Next(10);
                    return EmbedCS.Program.values[a] > EmbedCS.Program.values[b];
                }
            ");

            result = (bool)scriptFunction();
            Console.Read();
        }
    }
}

Remeber that, in C# everything is so implicit.

your func() is not a member of Program. So they can't recognize fields inside the Program.

Some dynamic languages have binding context(such as ruby's binding) in language level, so libraries can do black magic stuffs. but not in C#.