#命令行与文件读写
Lua 解释器把脚本收到的命令行参数放在表 arg 中。arg[0] 是脚本名,arg[1] 是第一个参数,arg[2] 是第二个。Shell 中用引号把带空格的文本或路径包成一个参数。
例如执行 lua write-note.lua "my note.txt" "Hello Lua" 时,#arg 为 2,arg[1] 和 arg[2] 分别是路径和文字。参数值以字符串传入,如果脚本需要数字,应先用 tonumber 转换并处理转换失败。
#选择打开模式
文件句柄记录当前读写位置,也负责管理缓冲区。使用 io.open(path, mode) 时,打开模式决定可以执行哪些操作,以及原文件的内容如何处理。
| 模式 | 用途 | 对原文件的影响 |
|---|---|---|
"r" | 从头读取 | 要求文件已存在 |
"w" | 从头写入 | 创建文件,已有内容会被清空 |
"a" | 在末尾追加 | 文件不存在时创建,已有内容保留 |
这些示例使用文本模式。读写图片等二进制数据时,可加上 b,例如用 "rb" 读取原始字节。
#写入文件
下面的脚本接收文件路径和一段文字,将文字写入文件。io.open(path, "w") 会创建文件,若文件已存在则清空原内容。打开失败时,io.open 返回 nil 和错误消息。
write-note.lua
if #arg ~= 2 then
io.stderr:write("用法:lua ", arg[0], " 文件路径 文字\n")
os.exit(2)
end
local file, open_error = io.open(arg[1], "w")
if not file then
io.stderr:write(open_error, "\n")
os.exit(1)
end
local written, write_error = file:write(arg[2], "\n")
local closed, close_error = file:close()
if not written or not closed then
io.stderr:write(write_error or close_error, "\n")
os.exit(1)
end
lua write-note.lua "my note.txt" "Hello Lua"
写入可能经过缓冲,所以关闭文件时也要检查错误。上面的脚本在写入失败后仍会尝试关闭文件。
#读取文件
下面用 "r" 以只读模式打开文件,并用 file:read("a") 读取全部内容。文件内容送到标准输出,错误消息送到标准错误,方便调用者单独重定向。
read-note.lua
if #arg ~= 1 then
io.stderr:write("用法:lua ", arg[0], " 文件路径\n")
os.exit(2)
end
local file, open_error = io.open(arg[1], "r")
if not file then
io.stderr:write(open_error, "\n")
os.exit(1)
end
local contents, read_error = file:read("a")
local closed, close_error = file:close()
if contents == nil or not closed then
io.stderr:write(read_error or close_error, "\n")
os.exit(1)
end
io.write(contents)
lua read-note.lua "my note.txt"
Hello Lua
#逐行读取与关闭文件
file:read("a") 读取全部内容,空文件会得到空字符串。file:read("l") 每次读取一行并去掉换行符,读到末尾时返回 nil。大量日志可以边读取边处理,只在内存中保留当前行和统计结果。
先运行前面的写入示例创建文件,再试着给每行加上行号。
local line_number = 0
for line in io.lines("my note.txt") do
line_number = line_number + 1
io.write(("%d %s\n"):format(line_number, line))
end
在 Lua 5.4 中,io.lines(path) 打开文件并把句柄交给泛型 for 管理,到达文件末尾、提前 break 或抛出错误都会关闭它。对已有句柄调用 file:lines() 时,句柄仍由打开它的代码管理,可以手动关闭,或交给 <close> 变量。
#分开处理结果与错误
两个示例使用相同的退出约定。参数个数不对时退出码为 2,文件操作失败时为 1,成功执行到脚本末尾时为 0。调用者可以读取退出码,决定是否继续下一步。下面把文件内容和错误消息写到不同的地方。
lua read-note.lua "my note.txt" > contents.txt 2> errors.txt