如何从Lua中的文件中读取数据

时间:2012-06-26 05:32:28

标签: lua

我想知道是否有办法从文件中读取数据,或者只是为了查看它是否存在并返回truefalse

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

4 个答案:

答案 0 :(得分:46)

试试这个:

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

答案 1 :(得分:9)

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

答案 2 :(得分:2)

有一个I/O library可用,但如果它可用取决于你的脚本主机(假设你已经在某处嵌入了lua)。如果您使用命令行版本,它可用。 complete I/O model很可能是您正在寻找的。

答案 3 :(得分:1)

如果想要逐行解析空格分隔的文本文件,只需添加一点。

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