I'm facing a problem of memory leak in Lua. To understand how the gc works I have written a small script and the results are surprising (for me):
local mt = { __gc = function() end }
local function new()
local o = { s = string.rep(os.date("%c"), 500) }
setmetatable(o, mt)
end
local before = math.floor(collectgarbage("count"))
for i = 1, 100000 do new() end
local after = math.floor(collectgarbage("count"))
print(before, after)
I'm creating 100000 objects, each objet has a metatable having a __gc function.
As result I get :
- with Lua 5.2.4 : 25 130 (25 kb of memory at start, 130 kb at the end of the script)
- with Lua 5.3.5 : 25 17470
Lua 5.3.5 does not garbage the objects as Lua 5.2.4 did.
I used the same script on different Lua versions (5.3.0, 5.3.1, 5.3.2, 5.3.3, 5.3.5) and this behaviour appears starting with Lua 5.3.2.
More surprising is that, if I remove the __gc function, the results are quite the same for all Lua versions.
Do you think that I'm missing something or is it a bug introduced in Lua 5.3.2 ?
Edit : this script behaves with Lua 5.4.0 as with Lua 5.3.1. So the bug is solved.