教程 lua tutorial

输入输出与文件操作

Lua 提供了丰富的 标准输入输出(I/O) 接口和文件操作函数,使脚本可以与用户交互或处理外部文件。

🖥️ 标准输出:print

lua
print("Hello, Lua!")
print("数字:", 123)

`

print 会自动在末尾换行,支持多个参数打印。

⌨️ 标准输入:io.read

lua
print("请输入你的名字:")
local name = io.read()  -- 默认读取一行
print("你好," .. name)
  • io.read("*n") 读取一个数字
  • io.read("*l") 读取一行(默认)
  • io.read("*a") 读取整个文件或输入流

📄 文件操作

Lua 使用 io.open 打开文件,file:read 和 file:write 操作文件内容。

lua
-- 打开文件写入
local file = io.open("test.txt", "w")
file:write("Hello Lua\n")
file:close()

-- 读取文件
local f = io.open("test.txt", "r")
local content = f:read("*a")  -- 读取整个文件
f:close()

print(content)  -- 输出:Hello Lua

文件模式说明

模式 含义
"r" 只读(文件必须存在)
"w" 只写(会清空已有内容)
"a" 追加写入
"r+" 读写(文件必须存在)
"w+" 读写(清空文件)
"a+" 读写(追加写入)

🔢 文件逐行读取

lua
local f = io.open("test.txt", "r")
for line in f:lines() do
  print(line)
end
f:close()

📐 字符串格式化

lua
local name = "Alice"
local score = 95
print(string.format("%s 的分数是 %d", name, score))
  • %s:字符串
  • %d:整数
  • %f:浮点数
  • 可配合 string.format 输出复杂格式

🧠 小结

  • 使用 print 与 io.read 进行标准输入输出
  • 文件操作通过 io.open, file:read, file:write 完成
  • 支持读取整行、整文件及逐行遍历
  • string.format 可进行字符串格式化