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

Optional parameters / params list #190

Open Xanatus opened 7 years ago

Xanatus commented 7 years ago

I'm wondering if there is any way in getting optional paramaters and/or params lists to work with c# class methods. It's kinda a pain in the ass making tons of overloads for everything.

If this is not already possible, this post can be considered as a feature request. Other libraries like NLua support this, so I guess it should be possible to implement.

rgarat commented 7 years ago

In theory some support already exists

http://www.moonsharp.org/objects.html#overload

Personally I never got it to work, and ended up just creating multiple methods manually

Xanatus commented 7 years ago

I know overloads work, but I would rather see support for optional arguments or even params that would work like lua func(...).

Something like: void Method(int a, int b = 2, string b = "unset") {} void Method(params DynValue[] args) {}

DaZombieKiller commented 7 years ago

You can do this with a CallbackFunction

static DynValue MyFunction(ScriptExecutionContext ctx, CallbackArguments args)
{
    var arguments = args.GetArray();

    // do stuff

    return DynValue.Nil;
}

And then add it to a table via:

table["myFunction"] = DynValue.NewCallback(MyFunction);

Xanatus commented 7 years ago

Thats good to know. Is there a way to make this work with class methods when you register an entire class?