0

当我遇到一点问题时,我正在尝试将 Lua 集成到我的 C# 应用程序中。我希望有更多专业知识的人可以帮助我指出正确的方向。

假设我有以下 C# 方法:

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

我想将它注册到我的 Lua 脚本环境中,这样我就可以执行以下操作:

-- call method with one param
MyMethod(123)
-- call method with two params
MyMethod(123, 456)

我尝试了 RegisterFunction("MyMethod", this, this.GetType().GetMethod("MyMethod")) 但它合理地抱怨不明确的匹配。有任何想法吗?

4

2 回答 2

2

模棱两可的方法异常实际上是由于调用GetMethod: 当参数GetMethod是一个字符串(方法名称)而没有Type[]为参数指定 a 并且该名称存在多个方法时,抛出异常。

如果您不必像问题中那样严格绑定单个方法,则可以注册该类,如LuaInterface 测试代码中所示

    private Lua _Lua;

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

        GC.Collect();  // runs GC to expose unprotected delegates
    }

    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)");
    }

这应该正确地调用你的重载。

否则,您将不得不调用GetMethod 重载,该重载采用 Type[] 参数并绑定到单独的 Lua 函数,或者坚持使用@Judge 的答案

于 2010-05-18T16:29:45.083 回答
0

您可以注册具有不同名称的函数,然后使用纯 Lua 函数通过检查参数来分派到正确的方法

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

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

于 2010-05-18T12:10:57.997 回答