41

trueファイルからデータを読み取る方法があるのか​​、それとも単にデータが存在するかどうかを確認して、またはを返す方法があるのだろうかと思っていました。false

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

4 に答える 4

75

これを試して:

-- 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
于 2012-06-26T09:58:51.407 に答える
22

テーブルにあるすべての関数を見つけることができるI/Oライブラリを使用してから、ファイルの内容を取得するために使用する必要があります。iofile: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);
于 2015-08-06T13:53:37.360 に答える
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
于 2017-09-19T09:49:59.500 に答える
2

利用可能なI/Oライブラリがありますが、利用できるかどうかはスクリプトホストによって異なります(luaをどこかに埋め込んだと仮定します)。コマンドラインバージョンを使用している場合は、これを使用できます。完全なI/Oモデルは、おそらくあなたが探しているものです。

于 2012-06-26T08:46:19.087 に答える