2

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?

KangarooRIOT
  • 691
  • 1
  • 7
  • 25
  • please elaborate "not working" – Piglet Jan 11 '22 at 08:24
  • The method I made simply is not allowing me to pass ing a list object into it. It exceptions out saying "Error processing file mapping: Object reference not set to an instance of an object." – KangarooRIOT Jan 11 '22 at 15:56
  • You know that NLua will try to find the mathods automatically using reflection. You don't need to manually register them. Take a look on the unit tests to see some use cases. – Vinicius Jarina Jan 11 '22 at 17:41
  • @ViniciusJarina I did not know that. Thank you! Do i just need to make a new lua in my using and that is all? I do not need to register anything at all? Do you know if you can pass an object in like a list to the methods? that is my issue – KangarooRIOT Jan 11 '22 at 17:46

1 Answers1

0

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
Frank Hale
  • 1,886
  • 1
  • 17
  • 31