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

48

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

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

https://dev59.com/Pm445IYBdhLWcg3wM3bx 或 http://stackoverflow.com/questions/5094417/how-do-i-read-until-the-end-of-file - Bart Kiers
4个回答

89

试试这个:

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

29

你应该使用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);

4

如果想逐行解析空格分隔的文本文件,可以添加以下内容。

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

2

有一个I/O库可用,但它是否可用取决于您的脚本主机(假设您已经嵌入了lua)。如果您使用命令行版本,则可以使用它。 完整的I/O模型很可能是您要寻找的。


如果这是一个游戏,我更喜欢添加自己的包装函数,可以从Lua中调用。否则,你会打开一个潘多拉魔盒,让人们通过插件/地图/附加组件破坏其他玩家的硬盘。 - Mario

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接