Мне было интересно, есть ли способ прочитать данные из файла или, возможно, просто посмотреть, существует ли он и вернуть true
или false
function fileRead(Path,LineNumber)
--..Code...
return Data
end
Мне было интересно, есть ли способ прочитать данные из файла или, возможно, просто посмотреть, существует ли он и вернуть true
или false
function fileRead(Path,LineNumber)
--..Code...
return Data
end
Попробуйте следующее:
-- 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
Вы должны использовать I/O Library, где вы можете найти все функции в таблице 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);
Там есть библиотека ввода/вывода, но, если она доступна, зависит от вашего хоста скриптов (если вы где-то вложили lua). Он доступен, если вы используете версию командной строки. полная модель ввода-вывода, скорее всего, то, что вы ищете.
Просто небольшое дополнение, если вы хотите разделить текстовый файл, разделенный пробелом, по строкам.
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