1

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.

6
  • 2
    It is not a bug regardless. Garbage collection is not, and never has been, promised to immediately remove unreachable objects. The system only promises to do so "eventually". Sep 26, 2019 at 13:37
  • It seems some GC parameters have been changed between 5.3.1 and 5.3.2 Sep 26, 2019 at 13:57
  • Even if I don't understant why the behavior is changing when __gc is defined, I will call collectgarbage() from time to time to reduce the memory usage. Sep 30, 2019 at 13:48
  • 1
    On the Lua mailing-list, I found something close to my question (lua-users.org/lists/lua-l/2017-07/msg00117.html). Perhaps will I also open a thread on the mailing-list to receive confirmation that it's the same bug (or not !) Oct 5, 2019 at 7:20
  • I made a test with Lua 5.4.0-beta and I get the same results as with Lua 5.2.4. I'll wait until Lua 5.4.0 is released to confirm that the bug is solved Nov 13, 2019 at 7:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.