《Lua快速入门》5.输入输出

Lua 提供了简单的标准输入输出功能,主要通过 `io` 库实现。标准输入输出包括从控制台读取输入和向控制台输出信息。

输入输出

1. 标准输入输出

1.1 标准输入输出概述

Lua 提供了简单的标准输入输出功能,主要通过 io 库实现。标准输入输出包括从控制台读取输入和向控制台输出信息。

1.2 标准输出

Lua 使用 printio.write 函数向标准输出(通常是控制台)写入数据。

1.2.1 print 函数

print 函数用于输出一个或多个值,每个值之间用制表符分隔,并在末尾自动添加换行符。

print("Hello, Lua!")  -- 输出: Hello, Lua!
print(10, 20, 30)     -- 输出: 10  20  30
1.2.2 io.write 函数

io.write 函数用于输出一个或多个值,不会自动添加分隔符和换行符。

io.write("Hello, Lua!")  -- 输出: Hello, Lua!
io.write(10, 20, 30)     -- 输出: 102030

1.3 标准输入

Lua 使用 io.read 函数从标准输入(通常是控制台)读取数据。

1.3.1 io.read 函数

io.read 函数可以读取一行输入或指定格式的数据。

local input = io.read()  -- 读取一行输入
print("You entered: " .. input)
1.3.2 读取指定格式的数据

io.read 支持多种读取模式:

  • "*n":读取一个数字。
  • "*a":读取整个文件内容。
  • "*l":读取一行(默认模式)。
  • "*L":读取一行并保留换行符。
  • n:读取 n 个字符。
local num = io.read("*n")  -- 读取一个数字
print("You entered: " .. num)

1.4 格式化输出

Lua 使用 string.format 函数进行格式化输出。

local name = "Lua"
local version = 5.4
print(string.format("Language: %s, Version: %.1f", name, version))
-- 输出: Language: Lua, Version: 5.4

2. 文件操作

2.1 文件操作概述

Lua 通过 io 库和 file 对象进行文件操作,包括文件的打开、读取、写入和关闭。

2.2 打开文件

使用 io.open 函数打开文件,返回一个文件对象。

local file = io.open("example.txt", "r")
if file then
    print("File opened successfully")
else
    print("Failed to open file")
end
2.2.1 文件打开模式
  • "r":只读模式(默认)。
  • "w":写入模式,覆盖文件内容。
  • "a":追加模式,在文件末尾添加内容。
  • "r+":读写模式,文件必须存在。
  • "w+":读写模式,覆盖文件内容。
  • "a+":读写模式,在文件末尾添加内容。

2.3 读取文件

使用文件对象的 read 方法读取文件内容。

2.3.1 读取一行
local file = io.open("example.txt", "r")
local line = file:read("*l")
print(line)
file:close()
2.3.2 读取整个文件
local file = io.open("example.txt", "r")
local content = file:read("*a")
print(content)
file:close()
2.3.3 逐行读取
local file = io.open("example.txt", "r")
for line in file:lines() do
    print(line)
end
file:close()

2.4 写入文件

使用文件对象的 write 方法向文件写入内容。

2.4.1 写入字符串
local file = io.open("example.txt", "w")
file:write("Hello, Lua!\n")
file:write(string.format("Version: %.1f\n", 5.4))
file:close()
2.4.2 追加内容
local file = io.open("example.txt", "a")
file:write("Appended line\n")
file:close()

2.5 关闭文件

使用文件对象的 close 方法关闭文件。

local file = io.open("example.txt", "r")
-- 文件操作
file:close()

2.6 文件定位

使用文件对象的 seek 方法移动文件指针。

2.6.1 获取当前位置
local file = io.open("example.txt", "r")
local pos = file:seek()  -- 获取当前位置
print("Current position: " .. pos)
file:close()
2.6.2 移动文件指针
local file = io.open("example.txt", "r")
file:seek("set", 10)  -- 移动到第 10 个字节
local content = file:read("*a")
print(content)
file:close()

2.7 文件状态

使用 io.type 函数检查文件对象的状态。

local file = io.open("example.txt", "r")
print(io.type(file))  -- 输出: file
file:close()
print(io.type(file))  -- 输出: closed file

3. 总结

Lua 的输入输出功能简单而强大,涵盖了标准输入输出和文件操作。通过掌握这些知识,您可以实现从控制台读取输入、向控制台输出信息,以及进行文件的读写操作。这些功能是 Lua 编程中不可或缺的一部分,广泛应用于脚本编写、数据处理和日志记录等场景。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页