Lua表内存泄漏?

Ker*_*ery 6 memory lua memory-leaks lua-table

我有关于lua表的使用的内存泄漏问题,代码如下:

function workerProc()
    -- a table holds some objects (userdata, the __gc is implememted correctly)
    local objs = {createObj(), createObj(), ...}
    while isWorking() do
        -- ...
        local query = {unpack(objs)}
        repeat
            -- ...
            table.remove(query, queryIndex)
        until #query == 0
        sleep(1000)
    end
end
Run Code Online (Sandbox Code Playgroud)

objs使用一些userdata对象初始化表,并且这些对象在while循环中始终可用,因此不会对这些obj执行gc.在while循环中,queryobjs使用来自(使用解包函数)的所有元素进行初始化.在运行脚本的过程中,我发现内存不断增加但是当我注释掉local query = {unpack(objs)}它时就会消失.

我不认为这段代码有内存泄漏问题导致queryvar是本地的,并且在每次迭代while循环后它应该是不可用的,但事实是.有谁知道为什么内存会被那个表吞噬?

gre*_*olf 7

从您的代码示例来看,您所看到的可能的解释可能是gc在循环内部没有机会执行完整的收集循环.

您可以在内部循环使用后立即强制收集,collectgarbage()并查看是否可以解决内存问题:

while isWorking() do
    -- ..
    local query = {unpack(objs)}
    repeat
        -- ..
        table.remove(query, queryIndex)
    until #query == 0
    collectgarbage()
    sleep(1000)
end
Run Code Online (Sandbox Code Playgroud)

另一种可能性是移出local query循环并创建表一次,而不是在outter循环中的每次迭代上创建一个新表.