user1465457
user1465457

Reputation:

How to read data from a file in Lua

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

Upvotes: 50

Views: 201213

Answers (4)

ryadav
ryadav

Reputation: 514

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

Upvotes: 4

netzzwerg
netzzwerg

Reputation: 406

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

Upvotes: 30

Bart Kiers
Bart Kiers

Reputation: 170158

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

Upvotes: 91

Mario
Mario

Reputation: 36487

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.

Upvotes: 2

Related Questions