是否可以将文本文件分配给变量并通过调用变量来访问文件?如果是这样,你怎么做?
问问题
333 次
3 回答
1
假设您想从一个函数中这样做。你将会拥有:
function writeToFile(_fileName) -- _fileName being the file you want to write to
local file = io.open(_fileName, "w")
file:write("This is a string that will be written to the file")
file:write("This is a second string")
file:flush( ) -- save the contents
file:close( ) -- stop accessing the file
end
如果您只想读取文件,那么您需要做的就是
function readFromFile(_fileName)
local file = io.open(_fileName, "r")
for line in file:lines() do
print(""..line.."\n")
end
end
于 2013-07-15T14:59:24.987 回答
1
使用IO 库
local input = assert(io.open(inputfile, "r"))
local data = f:read("*all")
--do some processing to data
local output = assert(io.open(outfule, "w"))
output:write(data)
input:close()
output:close()
于 2013-07-15T14:37:54.117 回答
1
如果您的意思是字面上的“调用变量”,那么试试这个:
local filename="/etc/passwd"
local f=assert(io.open(filename,"r"))
getmetatable(f).__call = f.read
repeat
local s=f()
print(s)
until s==nil
于 2013-07-15T15:51:06.897 回答