Why is lua crashing after extracting zip files?
I have the following code but it crashes every time it reaches the end of the function, but it successfully extracts all the files and puts them in the right location.
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
开发者_StackOverflow中文版 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\\")
Why does it crash every time it reaches the end?
Perhaps you need to call currFile:close()
after currFile:read()
in each iteration?
The problem is that LuaZip does not iterate over all open internal files and close them before closing the open zip file in which they are contained. Thus, the system crashes later when the garbage collector attempts to close the internal files that have had the rug pulled out from under them. So, simply removing the zfile:close()
line will also fix this crash because the garbage collector will release the userdata
in reverse order of allocation.
I'd want to discuss possible solutions with Danilo, Andre and Tomas before submitting a patch because some design decisions need to be made. For example, if an internal file is open when client code closes the zip file do you keep the zip file open until all internal files are released or invalidate open references to each internal file? Perhaps it should be left alone and users should be instructed to either (a) let the garbage collector handle closing all internal and zip files or (b) explicitly close all internal files before closing the containing zip file.
精彩评论