将文本文件分配到变量中

时间:2013-07-15 14:05:00

标签: lua variable-assignment

是否可以将文本文件分配给变量并通过调用变量来访问文件?如果是这样,你怎么做?

3 个答案:

答案 0 :(得分:1)

使用IO library

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

答案 1 :(得分: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

答案 2 :(得分: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