microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.77k stars 148 forks source link

evaluate without object name #492

Closed Tor012 closed 1 year ago

Tor012 commented 1 year ago

Is it possible to evaluate a property via the VBScript engine without having to specify its object explicitly. This was possible in the "old" MS ScriptControl.

Perhaps the property could be searched in all host objects or a main object could be defined.

Sample code follows

using System;
using System.Drawing;
using Microsoft.ClearScript;
using Microsoft.ClearScript.Windows;
using Microsoft.VisualBasic.CompilerServices;

namespace ConsoleApp1
{
    internal class Program
    {
        public static void Main()
        {
            using (var engine = new VBScriptEngine())
            {
                var vCar = new CarDef();
                vCar.name = "myCar";
                vCar.color = "yellow";

                engine.AddHostType(vCar.GetType());
                engine.AddHostObject("car", HostItemFlags.PrivateAccess, vCar);

                //ok
                Console.WriteLine(engine.Evaluate("car.color"));
                //not ok
                Console.WriteLine(engine.Evaluate("color"));
            }
            Console.ReadLine();
        }
    }

    public partial class CarDef
    {
        public string name { get; set; } = "";
        public string color { get; set; } = "";
    }
}
ClearScriptLib commented 1 year ago

Hello @Tor012,

You appear to be looking for "global members" functionality, where the members of an object are exposed as items at the global scope. ClearScript supports that feature via HostItemFlags:

var vCar = new CarDef { name = "myCar", color = "yellow" };
engine.AddHostObject("car", HostItemFlags.GlobalMembers, vCar);
Console.WriteLine(engine.Evaluate("car.color")); // OK
Console.WriteLine(engine.Evaluate("color")); // OK

Please let us know if that doesn't work for you. Thanks!

Tor012 commented 1 year ago

Thank you, that works perfect.

ClearScriptLib commented 1 year ago

Please reopen this issue if you have additional questions about this topic. Thank you!