neolithos / neolua

A Lua implementation for the Dynamic Language Runtime (DLR).
https://neolua.codeplex.com/
Apache License 2.0
467 stars 76 forks source link

Function overloading #85

Closed Symbai closed 5 years ago

Symbai commented 5 years ago

Is there a way to declare two functions with same name but different arguments? Like:

dg = lua.CreateEnvironment();
dg.printf = new Action<string>(StaticFunctions.printf);
dg.printf = new Action<int, string>(StaticFunctions.printf2);
printf("Hi") -- calls first
printf(0, "Hi") -- calls second
neolithos commented 5 years ago

Yes, it is possible:

public static void PrintByte(string message)
    => Console.WriteLine("PrintByte1: {0}", message);

public static void PrintByte(byte value, string message)
    => Console.WriteLine("PrintByte2: {0}: {1}", message, value);

static void Main(string[] args)
{
    var l = new Lua();
    var g = new LuaGlobal(l);
    dynamic dg = g;
    dg.printByte = new LuaOverloadedMethod(null,
        new MethodInfo[] {
        new Action<string>(PrintByte).Method,
        new Action<byte,string>(PrintByte).Method
    });
    g.DoChunk("printByte('Hi'); printByte(0x1, 'Hi');", "test.lua");
}
Symbai commented 5 years ago

Thank you