使用NLua在C#中注册和使用具有列表对象作为参数的函数

我目前正在使用NLua在一些C#代码中进行一些前端工作。使用/注册NLua时,我没有任何问题,但是一旦我想在方法中使用列表作为参数,它似乎就无法工作。

下面是目前有效的内容(去除了突出显示无法正常工作的内容):

enter image description here

上面引用的方法无法正常工作:

enter image description here


NLua不支持注册和使用对象函数吗?

点赞
用户170217
用户170217

NLua支持注册和使用作为对象的函数吗?

是的,您可以类似于您正在做的那样注册函数。您需要做的是传递包含您要注册方法的类的实例。

像这样:

var myApi = new API();
lua.RegisterFunction("add", myApi, typeof(API).GetMethod("Add"));

我通过将List更改为LuaTable来修复了您的'add'函数。我这样做是因为您从Lua传递到C#的数组实际上是Lua表。然后,您只需在C#端上迭代值并执行所需操作即可。

像这样:

public string Add(LuaTable target)
{
    List<int> targetsToAdd = new();

    foreach(var item in target.Values)
    {
        // FIXME: assuming item won't be null here
        targetsToAdd.Add(int.Parse(item.ToString()!));
    }

    int sum = targetsToAdd.Aggregate((x, y) => x + y);
    return sum.ToString();
}

然后在您的Lua脚本中,您可以这样做:

result = add({"2", "2"})
print(result) -- result = 4
2022-07-07 14:01:08