1

我有以下代码,但每次到达函数末尾时都会崩溃,但它成功地提取了所有文件并将它们放在正确的位置。

require "zip"

function ExtractZipAndCopyFiles(zipPath, zipFilename, destinationPath)
    local zfile, err = zip.open(zipPath .. zipFilename)

    -- iterate through each file insize the zip file
    for file in zfile:files() do
        local currFile, err = zfile:open(file.filename)
        local currFileContents = currFile:read("*a") -- read entire contents of current file
        local hBinaryOutput = io.open(destinationPath .. file.filename, "wb")

        -- write current file inside zip to a file outside zip
        if(hBinaryOutput)then
            hBinaryOutput:write(currFileContents)
            hBinaryOutput:close()
        end
    end

    zfile:close()
end
-- call the function
ExtractZipAndCopyFiles("C:\\Users\\bhannan\\Desktop\\LUA\\", "example.zip", "C:\\Users\\bhannan\\Desktop\\ZipExtractionOutput\\")

为什么每次到达终点都会崩溃?

4

2 回答 2

2

也许您需要在每次迭代中调用currFile:close()after ?currFile:read()

于 2010-05-14T02:27:38.557 回答
2

问题是 LuaZip 不会遍历所有打开的内部文件并在关闭包含它们的打开的 zip 文件之前关闭它们。因此,当垃圾收集器试图关闭已经从它们下面拉出地毯的内部文件时,系统会崩溃。因此,简单地删除该zfile:close()行也将修复此崩溃,因为垃圾收集器将以userdata相反的分配顺序释放。

在提交补丁之前,我想与 Danilo、Andre 和 Tomas 讨论可能的解决方案,因为需要做出一些设计决策。例如,如果在客户端代码关闭 zip 文件时打开了内部文件,您是否会保持 zip 文件打开直到所有内部文件都被释放或使对每个内部文件的打开引用无效?也许应该不理会它,并且应该指示用户(a)让垃圾收集器处理关闭所有内部和 zip 文件或(b)在关闭包含的 zip 文件之前明确关闭所有内部文件。

于 2010-05-14T14:29:49.393 回答