Can't fully collect garbage in Lua when it's embedded into C#

733 Views Asked by At

I'm using NLua to compile lua code from C#. The problem is that LuaTables created in C# can't be fully disposed by Lua garbage collector.

Here is the sample code:

        public static List<LuaTable> TempTables = new List<LuaTable>();

    static void Main(string[] args)
    {
        using (Lua lua = new Lua())
        {
            double mem = (double)lua.DoString("return collectgarbage(\"count\")")[0];
            for (int i = 0; i < 100000; i++)
            {
                LuaTable lt = NewTab(lua);
            }


            mem = (double)lua.DoString("return collectgarbage(\"count\")")[0];
            foreach (LuaTable lt in TempTables)
            {
                lt.Dispose();
            }
            TempTables.Clear();

            lua.DoString("collectgarbage()");
            mem = (double)lua.DoString("return collectgarbage(\"count\")")[0];
        }
    }
    public static LuaTable NewTab(Lua l)
    {            
        LuaTable lt = (LuaTable)l.DoString("return {}")[0];
        TempTables.Add(lt);
        return lt;
    }

This code simply creates 100 000 tables, then disposes it in C# and calls garbage collection in lua. Memory used can be inspected in variable "mem". The result is that "mem" will increase from 22.04Kb to approx. 1000Kb. It means that disposing this way will lead to memory leakages.

However, if we dispose LuaTable immedeately:

            for (int i = 0; i < 100000; i++)
            {
                LuaTable lt = NewTab(lua);
                lt.Dispose();
            }

It works well. The "mem" stays the same +-1Kb.

Why is it so? How should I dispose Lua objects to make it fully accessible to lua gc?

0

There are 0 best solutions below