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.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Francis P
  • 437
  • 1
  • 4
  • 13
  • 1
    Try calling `Enumerable.Count(audioMarkersWithOffset)` instead. Extension methods (such as the LINQ .Count() method) can be called like normal static methods. – cbr Jun 19 '15 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 Jun 19 '15 at 14:24
  • Hi Daniel, try to use : instead . `audioMarkersWithOffset:Count();` – Vinicius Jarina Jun 25 '15 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 Jun 26 '15 at 20:36
  • dot is only for static methods, instance methods should be called with `:` – Vinicius Jarina Jun 27 '15 at 23:44

1 Answers1

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).