Notulp/Pluton

Custom type converter for Jint2.

balu92 opened this issue · 9 comments

Custom type converter for Jint2.

A type converter has to be written for each specific instance of a C# type that we want to represent as a native JS structure. For example, a Dictionary<string, int> can be converted to a Javascript array of kvp objects:

[
{ "foo":3 },
{ "bar":7 },
...
]

If there's a Dictionary<string, bool> then another type converter is needed. The custom type converter is only written as-needed, and just for types we want to represent as JS types to Javascript.

So as I discover Javascript having to resort to explcitly calling GetEnumerator() in order to do something useful, I'll write a type converter for that object. That's where I'm headed with the LookUp stucture in JintPlugin.

Do your magic. :octocat:

I wanted to have this on Magma for the Player object. I ended up writing a "type converter" in Javascript, which used a template for the Player object that had the same structure as the Magma.Player class. The code walked the properties of Magma.Player, copying each property value to the template as a JS value. I could then use the JSON polyfill I found to store the Player object state in DS.

A custom type converter basically does the same thing, but hidden from JS. The Player object would just automatically look like a JS structure whenever JS saw it.

Sounds cool! Can't wait, but I guess it won't be a two-day project then.

It will require a bit of thought do it right for a complex object like Player. But a Dictionary<string, int> is easy.

do you need to only deal with the properties, or methods as well?

Depends. C# String, Int32, Single and Array are automatically type-converted to Javascript string, int, float and array types. Members of Player that return those types don't need conversion.

But for other types, like Vector3, I'm kind of torn. It's trivial to convert the coords to a 3-element array of floats that Javascript could use natively. Python would probably like it as a dictionary. But the Vector3 methods and operators are what make that type really useful, and that would be lost in a type conversion unless I get really elaborate. But why? If you understand how Vector3 works, you seldom need to break out the x,y,z separately. Vector addition/multiplication works just fine from Javascript.

So I am going to consider it on a case-by-case basis. What do plugin writers want to do with this object? Can they do it easier/better if it were represented as Javascript types? If yes, then I'll write a converter.

mike can we uncomment to allow jint2 plugins to be used? i have been writing some js plugins and only came across one difference in creating a plugin, which is changing a foreach loop, to a for and accessing the collection via the index

people want JS now, you good with that?

Of course.