LuaInterface - 如何注册重载方法?

我正在尝试将Lua集成到我的C#应用程序中,但遇到了一些小问题。希望更有经验的人能帮助我指导正确的方向。

假设我有以下C#方法:

` public void MyMethod(int foo) { ... } public void MyMethod(int foo, int bar) { ... } `

我想将其注册到我的Lua脚本环境中,以便我可以这样做:

` -使用一个参数调用方法 MyMethod(123) -调用具有两个参数的方法 MyMethod(123,456) `

我尝试了RegisterFunction(“MyMethod”,this,this.GetType()。GetMethod(“MyMethod”))但它合理地抱怨了关于模糊匹配。有什么想法吗?

点赞
用户1491
用户1491

你可以用不同的名称注册函数,然后使用一个纯 Lua 函数来分发正确的方法,通过检查参数

function MyMethod(foo, bar)
    if bar then
        MyMethod1(foo, bar)
    else
        MyMethod2(foo)
    end
end

或者,您可以在 C# 中实现此代理函数,并绑定它,而不是直接绑定每个重载方法。

2010-05-18 12:10:57
用户126042
用户126042

模糊方法异常实际上是由于调用GetMethod而引发的:当传递给GetMethod的参数是一个字符串(方法名称),但未指定Type []作为参数时,且存在超过一个此名称的方法时,将引发异常。

如果您不需要像您的问题一样严格绑定单个方法,您可以像[LuaInterface测试代码](http://code.google.com/p/luainterface/source/browse/trunk/luainterface/src/TestLuaInterface/TestLuaInterface.cs?r=6# 1058)演示的那样将类注册:

    private Lua _Lua;

    public void Init()
    {
        _Lua = new Lua();

        GC.Collect();  //运行GC以公开未受保护的委托
    }

    public void TestMethodOverloads()
    {
        Init();

        _Lua.DoString("luanet.load_assembly('mscorlib')");
        _Lua.DoString("luanet.load_assembly('TestLua')");
        _Lua.DoString("TestClass=luanet.import_type('LuaInterface.Tests.TestClass')");
        _Lua.DoString("test=TestClass()");
        _Lua.DoString("test:MethodOverload()");
        _Lua.DoString("test:MethodOverload(test)");
        _Lua.DoString("test:MethodOverload(1,1,1)");
        _Lua.DoString("test:MethodOverload(2,2,i)\r\nprint(i)");
    }

这应该正确调用您的重载函数。

否则,您将需要调用接受Type []参数的GetMethod重载,并绑定到单独的Lua函数,或者坚持@Judge的回答

2010-05-18 16:29:45