CSharp.lua icon indicating copy to clipboard operation
CSharp.lua copied to clipboard

Iterating "Native" lua tables in c#

Open fusspawn opened this issue 5 years ago • 2 comments

I have external methods that return lua tables Id like to iterate over.

/// <summary>
/// @CSharpLua.Template = "__LB__.GetObjects({0})"
/// </summary>
public extern string[] GetObjects(float Distance);

.... SNIP ... 
var objects = lb.GetObjects(100);
foreach (var GUID in objects) {
        Console.WriteLine($"Found GUID: {GUID}");
}

It seem's to generate fairly sane code for the most part.

Main = function (args)
      local lb = WrapperAPI.LuaBox()
      local objects = __LB__.GetObjects(100)
      for _, GUID in System.each(objects) do
        System.Console.WriteLine("Found GUID: " .. System.toString(GUID))
      end
    end

This will fail because it treats it as a .NET table and starts looking for an Enumerator due to the generated System.each that clearly wont exist on a native lua table. How do I work around this? Is it possible to trick CSharp lua into using pairs() around native tables instead of System.each

fusspawn avatar Feb 01 '21 11:02 fusspawn

Note. I managed to fix this by just having System.each return ipairs like it does for arrayEnumerator if getEnumerator returns nil. Will submit a patch following some more testing to make sure nothing else breaks.

fusspawn avatar Feb 01 '21 13:02 fusspawn

you can use a method to do this

class LuaHelper
  {
    public static void ArrayIpairs<T>(T[] array, Action<T> action)
    {
      /*
       [[
        for _, v in ipairs(array) do
          action(v)
        end
        ]]
       */ 
    }
  }

yanghuan avatar Feb 02 '21 07:02 yanghuan