文件操作
读取文件: io.open(“iter.lua”,“r”) 第一个参数应该是绝对路径
第二个参数:r 代表以只读方式打开,
w 代表以只写方式打开,会把文件中以前的内容删除重写;如果之前没有文件,则直接创建一个
a 代表以追加方式打开,是在原来文本的内容上继续追加。
function writeFile()
local file,msg = io.open("D:\\XXXXX\\iter.tex","w")
file:write("Hello world.\n")
file:flush()
file:close()
end
function readFile
local file,msg = io.open("D:\\XXXXX\\iter.tex","r")
if not file then
print(msg)
end
-- s = file:read("*all") --显示所有
-- s = file:read("*line") --只显示一行
--逐行读取
repeat
s = file.read()
if s ~= nil then
print(s)
else
break
end
until false
print(s) --hello world
end
例外处理
第一种方法:程序判断
function errorFun()
s = "15a"
if not tonumber(s) then
print("不是数字")
else
print("是数字")
end
end
第二种方法:抛出
pcall --用pcall 执行,后面是参数,如果有例外交给第二个参数msg,返回值也交给msg,无例外,第一个参数为true
b,mag = pcall(exceptionFun."rr") --此时结果:“这里提示异常文件以及第几行出错的” 这不等于的
b,mag = pcall(exceptionFun."dd") --此时结果:true 这等于的
print(b)
print(msg)
function exceptionFun(str)
if str ~= "dd" then
error("这不等于的")
end
return print("这等于的")
end