moonsharp-devs / moonsharp

An interpreter for the Lua language, written entirely in C# for the .NET, Mono, Xamarin and Unity3D platforms, including handy remote debugger facilities.
http://www.moonsharp.org
Other
1.42k stars 214 forks source link

Add a conversion to delegates #31

Closed xanathar closed 10 years ago

xanathar commented 10 years ago

https://groups.google.com/forum/#!topic/moonsharp/tSqnKSJn7_c

dibley1973 commented 10 years ago

Great to see you have added this to your backlog. In the mean time I have had a bit of a play about in my extensions project (see link below). You will see that they are a bit clumsy as you need a separate method for each number of parameters. I have not been able to find a better way to do this. Another issue with this is you would need to know exactly how many parameters the function expects to know the delegate you need to define. It would be nice if reflection or such like could be used to scrape the info from the Closure class.

I would assume from this whole Moonsharp project that your coding is much more advanced than mine so hopefully you will come up with a neater solution than mine.

ClosureExtensions.cs

xanathar commented 10 years ago

Hi, question solved I think.

public delegate object ScriptFunctionDelegate(params object[] args);
public delegate T ScriptFunctionDelegate<T>(params object[] args);

and in Closure.cs

    /// <summary>
    /// Gets a delegate wrapping calls to this scripted function
    /// </summary>
    /// <returns></returns>
    public ScriptFunctionDelegate GetDelegate()
    {
        return args => this.Call(args).ToObject();
    }

    /// <summary>
    /// Gets a delegate wrapping calls to this scripted function
    /// </summary>
    /// <typeparam name="T">The type of return value of the delegate.</typeparam>
    /// <returns></returns>
    public ScriptFunctionDelegate<T> GetDelegate<T>()
    {
        return args => this.Call(args).ToObject<T>();
    }

I will include these in the next release.

dibley1973 commented 10 years ago

That looks great, and a lot simpler than the way I was working. I'm looking forward to trying it out in the next release.

xanathar commented 10 years ago

Done. GetDelegate and GetDelegate methods in Closure.cs.