0Pricing
Lua Academy · Lesson

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) end

pcall 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) end

All lessons in this course

  1. Opening Files with io.open
  2. Reading File Contents
  3. Writing and Appending to Files
  4. Closing Files and Error Handling
← Back to Lua Academy