Lua - Closing Files
Lua provides I/O library to read and manipulate files. Now once file processing is complete, it is a good practice to call close() method. Although Lua does memory management automatically and close the resources.
Simple Model
io.close (file)
Where−
file− file handle .
Before closing a file, it should be opened using following syntax:
-- Opens a file specified by fileName in respective mode file = io.open(fileName, mode) -- sets the default input file io.input(file)
Complete Model
file:close ()
Where−
file− file handle returned by io.open().
Before writing a file, it should be opened using following syntax:
-- Opens a file specified by fileName in respectively mode file = io.open(fileName, mode)
But if we're opening multiple files and garbage collector is not running at that time then we may face following problems. −
Opened files may reach to maximum level until garbage collector closes them automatically.
Some platform may not allow to write to file if it is already opened and not closed.
Data may not be stored to a file by write() operation if close is not called.
Memory overflow can occur.
Example - Closing File in Simple Model
Let us now see how to close a file in simple model first.
main.lua
-- read a file content and returns the same
function readFile()
-- Opens a file in read
f = io.open("example.txt","r")
-- set the file as default input
io.input(f)
-- read first line
print(io.read())
-- read next line
print(io.read())
-- close the file
io.close()
-- return the contents
return contents
end
-- read the file
readFile()
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning
Example - Closing File in Complete Model
Let us now see how to close a file in complete model first.
main.lua
-- read a file content and returns the same
function readFile()
-- Opens a file in read
f = io.open("example.txt","r")
-- read first line
print(f:read())
-- read next line
print(f:read())
-- close the file
f:close()
-- return the contents
return contents
end
-- read the file
readFile()
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning