sebastienros / jint

Javascript Interpreter for .NET
BSD 2-Clause "Simplified" License
4.1k stars 563 forks source link

[Bug] function immidiately called #635

Closed MeikelLP closed 5 years ago

MeikelLP commented 5 years ago

I want to implement a (for now) basic modding interface for my Unity3D game.

I want to define a mod in module.exports styled manner:

module.exports = {
  name: 'Mod1',
  init () {
    registry.Add(new BlockPrototype('Dirt', 'assets/dirt.png'))
    registry.Add(new BlockPrototype('Grass', 'assets/grass.png'))
  }
}

And then call the individual phase while mod-loading (i.e. init). But sadly the function init is instantly called when I Engine.Execute this script block. This should not happen as I only define this function.

I tried to workaround this issue with defining the function separately as named function init () {} and then assign it but that didn't work as well.

lahma commented 5 years ago

What version of Jint? Running such script with latest preview version doesn't give an error even though registry is not defined.

MeikelLP commented 5 years ago

I'm not at work right now so I can't say for sure. I directly downloaded from nuget today. Should be 3.0.0-beta-1525. I'm adding more source code (especially C#) tomorrow.

Edit

I used nuget download Jint as dependecy @ 3.0.0-beta-1525. While stripping down my code I ran into another issue. I reply once I got a minimal example.

Edit 2

Somehow I'm now stuck with Unhandled Exception: System.InvalidCastException: Object must implement IConvertible. I can see why this happens (can't convert ExpandoObject to ModuleExports but is this by design? Can't I assign a "anonymous" Javascript object to my typed field/property?

I can make it work with explicitly defining the ModuleExports type but this completely kills the purpose of JS here (IMO).

var exports = new ModuleExports()
exports.name = 'Mod1'
exports.init = function () {
  registry.Add(new BlockPrototype('Dirt', 'assets/dirt.png'))
  registry.Add(new BlockPrototype('Grass', 'assets/grass.png'))
}

module.exports = exports

and

engine.SetValue(nameof(ModuleExports), TypeReference.CreateTypeReference(engine, typeof(ModuleExports)));
MeikelLP commented 5 years ago

I cannot reproduce this bug anymore. I don't know how it fixed itself :/