How to read data from a file in Lua

lua
user1465457 picture user1465457 · Jun 26, 2012 · Viewed 110k times · Source

I was wondering if there was a way to read data from a file or maybe just to see if it exists and return a true or false

function fileRead(Path,LineNumber)
  --..Code...
  return Data
end

Answer

Bart Kiers picture Bart Kiers · Jun 26, 2012

Try this:

-- http://lua-users.org/wiki/FileInputOutput

-- see if the file exists
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist
function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end

-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)

-- print all line numbers and their contents
for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end