yanghuan / CSharp.lua

The C# to Lua compiler
Other
1.23k stars 202 forks source link

Iterating "Native" lua tables in c# #343

Closed fusspawn closed 3 years ago

fusspawn commented 3 years ago

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 commented 3 years ago

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.

yanghuan commented 3 years ago

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
        ]]
       */ 
    }
  }