Lua 教程 - 第九章:标准库
第九章:标准库
Lua 为了保持轻量级,核心语言非常小。但它提供了一组实用的标准库,涵盖了常用的功能。这些库由 C 语言实现,效率极高。
前面几章我们已经介绍了 string, table, io, debug 库。本章将重点介绍 math (数学) 和 os (操作系统) 库。
9.1 数学库 (math)
math 库包含了常用的数学函数。
常用三角函数
-
math.sin(x),math.cos(x),math.tan(x): 参数x为弧度。 -
math.deg(x): 弧度转角度。 -
math.rad(x): 角度转弧度。
print(math.sin(math.pi / 2)) -- 1.0
print(math.deg(math.pi)) -- 180.0
取整与绝对值
-
math.floor(x): 向下取整。 -
math.ceil(x): 向上取整。 -
math.abs(x): 绝对值。 -
math.fmod(x, y): 取模(浮点数)。
print(math.floor(3.7)) -- 3
print(math.ceil(3.2)) -- 4
随机数
-
math.random(): 返回 [0, 1) 之间的伪随机浮点数。 -
math.random(n): 返回 [1, n] 之间的伪随机整数。 -
math.random(m, n): 返回 [m, n] 之间的伪随机整数。 -
math.randomseed(x): 设置随机数种子。重要:通常在程序开始时使用os.time()作为种子,否则每次运行产生的随机序列都一样。
math.randomseed(os.time())
print(math.random(1, 100))
其他
-
math.min(x, ...): 最小值。 -
math.max(x, ...): 最大值。 -
math.sqrt(x): 平方根。 -
math.exp(x): e 的 x 次幂。 -
math.log(x): 自然对数。 -
math.huge: 表示无穷大。
mindmap
root((math 数学库))
三角函数
sin cos tan
deg 弧度转角度
rad 角度转弧度
取整与绝对值
floor 向下取整
ceil 向上取整
abs 绝对值
fmod 取模
随机数
random 生成随机数
randomseed 设置种子
其他函数
min 最小值
max 最大值
sqrt 平方根
exp 对数幂
log 自然对数
huge 无穷大
9.2 操作系统库 (os)
os 库提供了与操作系统交互的功能,如日期时间、文件系统操作等。
日期和时间
-
os.time([table]): 返回当前时间戳(秒数)。如果传入表,则返回该表描述的时间的时间戳。 -
os.date([format [, time]]): 格式化时间。%Y: 年 (2026)%m: 月 (02)%d: 日 (15)%H: 时 (24小时制)%M: 分%S: 秒*t: 返回一个包含year,month,day,hour,min,sec,wday(星期几),yday(一年中的第几天),isdst(夏令时) 的表。
print(os.time()) -- 1771234567
local t = os.date("*t")
print(t.year, t.month, t.day)
print(os.date("%Y-%m-%d %H:%M:%S")) -- 2026-02-15 12:00:00
进程控制
-
os.execute([command]): 执行系统命令。等同于 C 语言的system。 -
os.exit([code]): 终止程序执行。 -
os.getenv(varname): 获取环境变量的值。
os.execute("ls -la") -- 列出当前目录文件
print(os.getenv("HOME")) -- 打印用户主目录
文件系统操作
-
os.remove(filename): 删除文件。 -
os.rename(oldname, newname): 重命名文件。 -
os.tmpname(): 返回一个可用于临时文件的文件名(并不创建文件)。
os.remove("junk.txt")
性能计时
-
os.clock(): 返回程序使用的 CPU 时间(秒)。常用于性能测试。
local start = os.clock()
local s = 0
for i = 1, 1000000 do s = s + i end
print("Elapsed time: " .. os.clock() - start)
flowchart TD
A[os 操作系统库] --> B[日期时间]
A --> C[进程控制]
A --> D[文件系统]
A --> E[性能计时]
B --> B1[os.time]
B --> B2[os.date]
C --> C1[os.execute]
C --> C2[os.exit]
C --> C3[os.getenv]
D --> D1[os.remove]
D --> D2[os.rename]
D --> D3[os.tmpname]
E --> E1[os.clock]
style A fill:#e3f2fd
style B fill:#a5d6a7
style C fill:#ffcc80
style D fill:#90caf9
style E fill:#ce93d8
练习题
-
编写一个函数
get_random_string(len),生成一个指定长度的随机字符串(包含字母和数字)。 -
编写一个函数,计算两个日期之间相差的天数。提示:使用
os.time获取时间戳相减。 -
使用
math库实现一个简单的蒙特卡洛算法来估算圆周率 Pi 的值。 -
编写一个脚本,每天凌晨 0 点自动备份某个文件(通过
os.date检查时间,配合os.execute执行复制命令,注意:这通常在系统 cron 中做,但用 Lua 练习一下逻辑)。
下一章预告:Lua 最强大的功能之一是与 C 语言的互操作性。下一章我们将揭开 Lua C API 的神秘面纱,学习如何在 Lua 中调用 C 函数,以及如何在 C 程序中嵌入 Lua。
