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

28 lua

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

function fileRead(Path,LineNumber)
  --..Code...
  return Data
end
Run Code Online (Sandbox Code Playgroud)

Bar*_*ers 49

试试这个:

-- 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
Run Code Online (Sandbox Code Playgroud)


小智 11

您应该使用I/O库,您可以在其中找到io表中的所有函数,然后使用它file:read来获取文件内容.

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);
Run Code Online (Sandbox Code Playgroud)