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

Engine in VB.NET returning "nothing" to host #596

Closed juan-nxlevel closed 2 months ago

juan-nxlevel commented 2 months ago

Dear ClearScript, In the following code:

    Script = New VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging)
    Script.EnableNullResultWrapping = True 
    Script.AddHostType(GetType(Console))

    Dim doc As XmlDocument = New XmlDocument()
    doc.LoadXml("<root><page id=""1""/><page id=""2""/><page id=""3""/></root>")
    Script.AddHostObject("page", doc.DocumentElement)
    Script.Execute("
        set p = page.selectSingleNode(""text"")
        console.write(p is nothing)
    ")

with: Public Class Console Public Shared Sub Write(obj As Object) If obj Is Nothing Then Debug.Print("Object is Nothing") Else Debug.Print(obj.ToString()) End If End Sub End Class

Which results in this output:

False

Since the node "text" doesnt exist, shouldn't return "True" ? (If i take out the EnableNullResultWrapping then I can't evaluate selectSingleNode). Thanks for any suggestions!

ClearScriptLib commented 2 months ago

Hi @juan-nxlevel,

Since the node "text" doesnt exist, shouldn't return "True" ?

Since you're using EnableNullResultWrapping, no. From the documentation: "Note that such values will always fail equality comparison with JavaScript's null, VBScript's Nothing, and other similar values."

Thanks for any suggestions!

Although ClearScript's defaults – and even some of its API names – are skewed in favor of C# and JavaScript, there may be a way to get the behavior you're looking for with VB and VBScript.

The problem is that there's no obvious mapping between .NET's null/Nothing and the various constants that script languages use to represent undefined, uninitialized, unknown, or missing data. The rules that ClearScript uses to marshal those values are complicated and not necessarily optimal in all cases.

You can adjust some aspects of ClearScript's behavior by using the script engine's NullExportValue and UndefinedImportValue properties. Here's a modified sample that demonstrates their usage:

Dim Script = New VBScriptEngine(WindowsScriptEngineFlags.EnableDebugging)
Script.NullExportValue = Microsoft.ClearScript.Windows.Nothing.Value
Script.UndefinedImportValue = Nothing
Script.AddHostType(GetType(Console))
Dim doc = New XmlDocument()
doc.LoadXml("<root><page id=""1""/><page id=""2""/><page id=""3""/></root>")
Script.AddHostObject("page", doc.DocumentElement)
    Script.Execute("
    set p = page.selectSingleNode(""text"")
    console.write(p)
    console.write(p is nothing)
")

It produces the following output:

Object is Nothing
True

Please let us know if this solution works for you. Thanks!

juan-nxlevel commented 2 months ago

Perfect! Thank you very much!