0

So I have a little lua script where I want to call an extension method on IEnumerable collection.

require ''CLRPackage''
import ''System.Collections.Generic''
import ''System.Linq''
import ''My.Namespace.Containing.AudioMarker''

local audioMarkersWithOffset = GetAudioMarkers();
local numberOfMarkers = audioMarkersWithOffset.Count();

So GetAudioMarkers() is a C# method returning an IEnumerable of AudioMarker objects. Doing a luanet.each will work fine and I will be able to iterate to every element of the collection. But I need the count of that collection and calling .Count() does the following error: NLua.Exceptions.LuaScriptException: [string "chunk"]:54: attempt to call field 'Count' (a string value).

By the way, I know that with nlua you don't need to pre-register your types to used them so I try with and without the last import about AudioMarker, but got the same result.

I'm probably doing something wrong but I cannot seem to find any documentation on the web that could help regarding this issue.

5
  • 1
    Try calling Enumerable.Count(audioMarkersWithOffset) instead. Extension methods (such as the LINQ .Count() method) can be called like normal static methods.
    – cbr
    Commented Jun 19, 2015 at 13:59
  • Still does not work. The error is: NLua.Exceptions.LuaScriptException: [string "chunk"]:156: attempt to index global 'Enumerable' (a nil value). And I did check that audioMarkersWithOffset was not nil and it's the case.
    – Francis P
    Commented Jun 19, 2015 at 14:24
  • Hi Daniel, try to use : instead . audioMarkersWithOffset:Count(); Commented Jun 25, 2015 at 19:38
  • Won't work : I'm calling .net methods with a dot not a colon and it's working when methods are not extensions methods
    – Francis P
    Commented Jun 26, 2015 at 20:36
  • dot is only for static methods, instance methods should be called with : Commented Jun 27, 2015 at 23:44

1 Answer 1

2

I have been trying to use the IEnumerable<T>.ToList() extension method myself, but testing reveals that NLua has some problems with generic methods.. Calling a method of the form void func<T>(<T> arg) is possible if you register it as a lua function (Lua.RegisterFunction), but if you try to call the same method on an object present in lua state, you get the "attempt to call method..." error. Also, a method of the form void func<T>(IEnumerable<T> arg) will fail in both cases with a NullReferenceException and the "attempt to call method..." error, respectively.

Another point is, if you want to call C# extension methods from Lua, you need the ":" syntax, not "." (see the NLua "TestExtensionMethods" unit test).

1
  • Thanks for thatinsight, it was really helpful
    – Francis P
    Commented Aug 22, 2015 at 20:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.