|
Hi
I noticed I have a bad memory leak in my C# program where I use LuaInterface to add Lua Scripting. I wrote a small test program to investigate further.
I have a C# method that returns a big string and a big table back to Lua. I then call this repatedly in a loop and monitor Ram usage.
public void testMem(out LuaTable resultsTable, out string testStr)
{ resultsTable = null; var rnd = new Random(); var sb = new StringBuilder(20000); for (int i = 0; i < 15000; i++) sb.Append( (char)rnd.Next(0x20, 0x7f) ); testStr = sb.ToString(); lua.NewTable("tab"); LuaTable tab1 = lua.GetTable("tab"); for (int i = 0; i < 20000; i++) tab1[i] = i * 10; resultsTable = tab1; } The string creation got a clean bill of health, no leak there, it was the table creation that causes the leak.
The above code is wrong in that every time this function is called it will allocate memory in lua.NewTable("tab"); the reference to this must get lost next time it is called and I have orphaned memory.
I can reduce the size of the leak by changing it to
LuaTable tab1;
tab1 = lua.GetTable("tab"); if (tab1 == null) { lua.NewTable("tab"); tab1 = lua.GetTable("tab"); }
This isnt really a good fix though as the first NewTable() call will allocate memory which I cannot figure out how to reclaim.
I have tried to reclaim the memory alloc several ways, setting tab1 = null or tab1.Dispose(). Also tried reclaiming it on the Lua side local tab, str = myAPILibs.testMem() print( str) tab, str = nil, nil -- I called the garbage collector after this line None of these experiments seem to reclaim the initial memory allocation ? The documentation for LuaInterface is very lacking, so I have no idea how this table should be reclaimed, I am guessing the Lua side should have responsibilty for marking the table as used so the GC can clean up. I would appreciate someone explaining how a simple table allocation like this should be cleaned up so it doesnt leak like a sieve ! Thanks Geoff
|