NLua in C# Registering and Using a function that has a List object as a parameter

727 Views Asked by At

I am currently using NLua in some C# code for some front-end work. I have had no issues at all using/registering non-objects with NLua but the moment I want to use a List as a parameter in a method; it does not seem to work.

This is what I have currently that works (minus the highlighted which shows what is not working):

enter image description here

This is the method that is referenced above that is not working:

enter image description here


Does NLua not support registering and using functions that are objects?

1

There are 1 best solutions below

0
Frank Hale On

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