Cannot call .Count() IEnumerable extensions from lua script using nula

624 views Asked by At

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.

1

There are 1 answers

1
Jesper Matthiesen On BEST ANSWER

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