yanghuan / CSharp.lua

The C# to Lua compiler

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Switch clause with type matching does not work

joelverhagen opened this issue · comments

Repro:

internal class Program
{
    private static void Main()
    {
        BaseEntity entity = new EntityB();
        switch (entity)
        {
            case EntityA:
                Console.WriteLine("A");
                break;
            case EntityB:
                Console.WriteLine("B");
                break;
            default:
                Console.WriteLine("none");
                break;
        }
    }

    private class BaseEntity
    {
    }

    private class EntityA : BaseEntity
    {
    }

    private class EntityB : BaseEntity
    {
    }
}

The generate Lua appears to be comparing the input instance reference to the type itself (something like comparing Entity to System.Type).

Generated Lua:

-- Generated by CSharp.lua Compiler
do
local System = System
System.namespace("", function (namespace)
  namespace.class("Program", function (namespace)
    local Main, class
    namespace.class("BaseEntity", function (namespace)
      return {}
    end)
    namespace.class("EntityA", function (namespace)
      return {
        base = function (out)
          return {
            out.Program.BaseEntity
          }
        end
      }
    end)
    namespace.class("EntityB", function (namespace)
      return {
        base = function (out)
          return {
            out.Program.BaseEntity
          }
        end
      }
    end)
    Main = function ()
      local entity = class.EntityB()
      repeat
        local default = entity
        if default == class.EntityA then
          System.Console.WriteLine("A")
          break
        elseif default == class.EntityB then
          System.Console.WriteLine("B")
          break
        else
          System.Console.WriteLine("none")
          break
        end
      until 1
    end
    class = {
      Main = Main
    }
    return class
  end)
end)

end
System.init({
  types = {
    "Program",
    "Program.BaseEntity",
    "Program.EntityA",
    "Program.EntityB"
  }
})

Program.Main()

An easy workaround is to use a sequence of if / else with is conditions, e.g.

        BaseEntity entity = new EntityB();
        if (entity is EntityA)
        {
            Console.WriteLine("A");
        }
        else if (entity is EntityB)
        {
            Console.WriteLine("B");
        }
        else
        {
            Console.WriteLine("none");
        }