48

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
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • http://stackoverflow.com/questions/4990990/lua-check-if-a-file-exists or http://stackoverflow.com/questions/5094417/how-do-i-read-until-the-end-of-file – Bart Kiers Jun 26 '12 at 08:47

4 Answers4

88

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
  local 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
Mud
  • 28,277
  • 11
  • 59
  • 92
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
28

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);
Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
netzzwerg
  • 386
  • 4
  • 9
4

Just a little addition if one wants to parse a space separated text file line by line.

read_file = function (path)
local file = io.open(path, "rb") 
if not file then return nil end

local lines = {}

for line in io.lines(path) do
    local words = {}
    for word in line:gmatch("%w+") do 
        table.insert(words, word) 
    end    
  table.insert(lines, words)
end

file:close()
return lines;
end
Axel
  • 3,331
  • 11
  • 35
  • 58
ryadav
  • 456
  • 5
  • 11
2

There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

Mario
  • 35,726
  • 5
  • 62
  • 78
  • If it's going to be a game, I'd prefer adding your own wrapper function that can be called from Lua. Otherwise you're opening up a can of worms, by granting people the possibilities to screw up other players' hard disks through addons/maps/plugins. – Mario Jun 26 '12 at 09:49