Does NLua not support registering and using functions that are objects?
Yes, you can register functions similar to what you are doing. What you need to do is pass an instance of the class that contains the method you are registering.
Like this:
var myApi = new API();
lua.RegisterFunction("add", myApi, typeof(API).GetMethod("Add"));
I was able to fix your 'add' function by changing the List to a LuaTable. I did this because the array you are passing from Lua to C# is actually a Lua table. You can then just iterate over the values on the C# side and do what you need to do.
Like this:
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();
}
Then in your Lua script you can do:
result = add({"2", "2"})
print(result) -- result = 4