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

我想知道是否有一种方法可以从文件中读取数据,或者只是检查文件是否存在并返回 truefalse

function fileRead(Path,LineNumber)
  --..Code...
  return Data
end
点赞
用户409744
用户409744

有一个I/O库可供使用,但是否可用取决于你的脚本宿主(假设你已将Lua嵌入某个地方)。如果你使用的是命令行版本,它是可用的。完整的I/O模型很可能是你正在寻找的内容。

2012-06-26 08:46:19
用户50476
用户50476

尝试这样做:

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

-- 检查文件是否存在
function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

-- 获取文件中的所有行, 如果文件不存在则返回一个空列表/表
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

-- 测试上面的函数
local file = 'test.lua'
local lines = lines_from(file)

-- 打印所有行号及其内容
for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end
2012-06-26 09:58:51
用户516271
用户516271

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

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r 读取模式和 b 二进制模式
    if not file then return nil end
    local content = file:read "*a" -- *a 或 *all 读取整个文件
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);
2015-08-06 13:53:37
用户7237628
用户7237628

如果想逐行解析用空格分隔的文本文件,可以添加以下代码:

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
2017-09-19 09:49:59