【问题标题】:How to read data from a file in LuaLua如何从文件中读取数据
【发布时间】:2012-06-27 09:54:04
【问题描述】:

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

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

【问题讨论】:

标签: lua


【解决方案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

【讨论】:

    【解决方案2】:

    您应该使用I/O Libraryio 表中找到所有函数,然后使用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);
    

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

        • 如果它是一个游戏,我更喜欢添加你自己的可以从 Lua 调用的包装函数。否则,您将通过插件/地图/插件授予人们破坏其他玩家硬盘的可能性,从而打开一罐蠕虫。
        猜你喜欢
        • 2020-07-13
        • 2021-12-19
        • 2017-01-18
        • 2015-07-05
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        • 2015-04-12
        • 1970-01-01
        相关资源
        最近更新 更多