Closing Files and Error Handling
Close file handles properly and handle io errors with pcall.
Always Close Files
Every file opened with io.open must be closed with f:close(). Unclosed files leak file descriptors. Lua's GC will eventually close them, but you can exhaust OS file limits before GC runs. Always close in the function that opened the file.
local function readFile(path)
local f, err = io.open(path, "r")
if not f then return nil, err end
local content = f:read("a")
f:close() -- always close
return content
end
local data, err = readFile("config.txt")
if not data then print("Error:", err) endpcall for IO Safety
Wrap file operations in pcall to catch unexpected errors (disk full, permission denied mid-write). This ensures you handle errors gracefully rather than crashing the program.
local function safeCopy(src, dst)
local ok, err = pcall(function()
local f = io.open(src, "rb")
if not f then error("Cannot open source: " .. src) end
local content = f:read("a")
f:close()
local g = io.open(dst, "wb")
if not g then error("Cannot open dest: " .. dst) end
g:write(content)
g:close()
end)
return ok, err
end
local ok, msg = safeCopy("input.txt", "output.txt")
if not ok then print("Failed:", msg) endAll lessons in this course
- Opening Files with io.open
- Reading File Contents
- Writing and Appending to Files
- Closing Files and Error Handling