Lua 标准库指南

简介

本指南详细介绍了 Lua 中的标准库,包括 string、math、os、io、table、debug、coroutine 和 package 等库的使用方法。通过本指南,您将学习如何在 Lua 中有效地使用这些标准库,提高代码的效率和可读性。

目录

  1. string 库(字符串操作)
  2. math 库(数学函数)
  3. os 库(操作系统交互)
  4. io 库(文件操作)
  5. table 库(表操作)
  6. debug 库(调试功能)
  7. coroutine 库(协程)
  8. package 库(模块管理)
  9. 实用工具函数
  10. 标准库最佳实践
  11. 常见问题与解决方案

1. string 库(字符串操作)

string 库提供了丰富的字符串操作函数,包括字符串长度计算、大小写转换、截取、查找、替换、格式化等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
local str = "Hello, Lua Programming!"
print("Original string:", str)

-- 1.1 字符串长度
print("Length:", string.len(str))
print("Length (using #):", #str)

-- 1.2 字符串大小写转换
print("Uppercase:", string.upper(str))
print("Lowercase:", string.lower(str))

-- 1.3 字符串截取
print("Substring (1-5):", string.sub(str, 1, 5))
print("Substring (8-end):", string.sub(str, 8))
print("Substring (from end):", string.sub(str, -11))

-- 1.4 字符串查找
local start_pos, end_pos = string.find(str, "Lua")
print("Find 'Lua':", start_pos, end_pos)

-- 1.5 字符串替换
local new_str = string.gsub(str, "Lua", "LUA")
print("Replace 'Lua' with 'LUA':", new_str)

-- 1.6 字符串格式化
local formatted = string.format("%s is %d years old and has %.2f GPA", "Alice", 25, 3.85)
print("Formatted string:", formatted)

-- 1.7 字符串重复
print("Repeat 'Hi ' 3 times:", string.rep("Hi ", 3))

-- 1.8 字符串匹配(正则表达式)
local email = "user@example.com"
local username = string.match(email, "(%a+)@")
local domain = string.match(email, "@(%a+%.%a+)")
print("Email parts - username:", username, "domain:", domain)

-- 1.9 字符串分割(使用gmatch)
local csv = "apple,banana,orange,grape"
local fruits = {}
for fruit in string.gmatch(csv, "[^,]+") do
table.insert(fruits, fruit)
end
print("Split CSV:", table.concat(fruits, " | "))

常用函数表

函数 描述 示例
string.len(s) 计算字符串长度 string.len(“hello”) → 5
string.upper(s) 转换为大写 string.upper(“hello”) → “HELLO”
string.lower(s) 转换为小写 string.lower(“HELLO”) → “hello”
string.sub(s, i, j) 截取字符串 string.sub(“hello”, 1, 3) → “hel”
string.find(s, pattern) 查找子串 string.find(“hello”, “ll”) → 3, 4
string.gsub(s, pattern, replacement) 替换子串 string.gsub(“hello”, “l”, “x”) → “hexxo”
string.format(format, …) 格式化字符串 string.format(“%.2f”, 3.14159) → “3.14”
string.rep(s, n) 重复字符串 string.rep(“hi”, 3) → “hihihi”
string.match(s, pattern) 匹配字符串 string.match(“user@example.com“, “(%a+)@”) → “user”
string.gmatch(s, pattern) 迭代匹配 for word in string.gmatch(“hello world”, “%a+”) do … end

2. math 库(数学函数)

math 库提供了各种数学函数,包括基本数学运算、三角函数、指数和对数、随机数生成等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-- 2.1 基本数学运算
print("math.abs(-10):", math.abs(-10))
print("math.floor(3.7):", math.floor(3.7))
print("math.ceil(3.2):", math.ceil(3.2))
print("math.sqrt(16):", math.sqrt(16))

-- 2.2 三角函数
print("math.sin(math.pi/2):", math.sin(math.pi/2))
print("math.cos(math.pi):", math.cos(math.pi))
print("math.tan(math.pi/4):", math.tan(math.pi/4))
print("math.asin(1):", math.asin(1))

-- 2.3 指数和对数
print("math.exp(1):", math.exp(1))
print("math.log(math.exp(1)):", math.log(math.exp(1)))
print("math.log10(100):", math.log10(100))
print("math.pow(2, 10):", math.pow(2, 10))

-- 2.4 最大最小值
print("math.max(10, 5, 20, 15):", math.max(10, 5, 20, 15))
print("math.min(10, 5, 20, 15):", math.min(10, 5, 20, 15))

-- 2.5 随机数
math.randomseed(os.time()) -- 设置随机种子
print("Random (0-1):", math.random())
print("Random (1-10):", math.random(10))
print("Random (5-15):", math.random(5, 15))

-- 2.6 常量
print("math.pi:", math.pi)
print("math.huge:", math.huge)

常用函数表

函数 描述 示例
math.abs(x) 绝对值 math.abs(-10) → 10
math.floor(x) 向下取整 math.floor(3.7) → 3
math.ceil(x) 向上取整 math.ceil(3.2) → 4
math.sqrt(x) 平方根 math.sqrt(16) → 4
math.sin(x) 正弦 math.sin(math.pi/2) → 1
math.cos(x) 余弦 math.cos(math.pi) → -1
math.tan(x) 正切 math.tan(math.pi/4) → 1
math.exp(x) 指数 math.exp(1) → 2.71828…
math.log(x) 自然对数 math.log(math.exp(1)) → 1
math.log10(x) 常用对数 math.log10(100) → 2
math.pow(x, y) 幂运算 math.pow(2, 10) → 1024
math.max(…) 最大值 math.max(1, 5, 3) → 5
math.min(…) 最小值 math.min(1, 5, 3) → 1
math.random(…) 随机数 math.random(1, 10) → 5 (随机)
math.randomseed(x) 设置随机种子 math.randomseed(os.time())

常量

常量 描述
math.pi 圆周率 3.141592653589793
math.huge 无穷大 1.#INF

3. os 库(操作系统交互)

os 库提供了与操作系统交互的功能,包括时间函数、执行系统命令、获取环境变量等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-- 3.1 时间函数
print("os.time():", os.time())
print("os.date():", os.date())
print("os.date('%Y-%m-%d'):", os.date("%Y-%m-%d"))
print("os.date('%H:%M:%S'):", os.date("%H:%M:%S"))

-- 3.2 执行系统命令
print("\nExecute system command 'echo Hello':")
local handle = io.popen("echo Hello")
if handle then
local result = handle:read("*a")
print("Result:", result)
handle:close()
end

-- 3.3 获取环境变量
print("\nos.getenv('PATH'):", os.getenv("PATH"))

-- 3.4 其他os函数
print("os.clock():", os.clock())
print("os.difftime(os.time(), os.time() - 3600):", os.difftime(os.time(), os.time() - 3600))

常用函数表

函数 描述 示例
os.time([table]) 获取当前时间或转换时间表 os.time() → 1620000000
os.date([format [, time]]) 格式化时间 os.date(“%Y-%m-%d”) → “2021-05-03”
os.clock() 程序运行时间 os.clock() → 0.123
os.difftime(t2, t1) 时间差 os.difftime(os.time(), os.time()-3600) → 3600
os.execute([command]) 执行系统命令 os.execute(“dir”)
os.getenv(varname) 获取环境变量 os.getenv(“PATH”)
os.remove(filename) 删除文件 os.remove(“test.txt”)
os.rename(oldname, newname) 重命名文件 os.rename(“old.txt”, “new.txt”)
os.tmpname() 生成临时文件名 os.tmpname() → “tmp0000000001”

时间格式化字符串

格式 描述 示例
%Y 四位年份 2021
%m 两位月份 05
%d 两位日期 03
%H 24小时制小时 14
%M 分钟 30
%S 45
%a 缩写星期名 Sun
%A 完整星期名 Sunday
%b 缩写月份名 May
%B 完整月份名 May
%c 本地日期和时间 05/03/21 14:30:45
%x 本地日期 05/03/21
%X 本地时间 14:30:45

4. io 库(文件操作)

io 库提供了文件操作的功能,包括打开文件、读写文件、关闭文件等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
-- 4.1 标准输入输出
print("\nStandard I/O:")
-- io.write("Enter your name: ")
-- local name = io.read()
-- print("Hello, " .. name)

-- 4.2 临时文件
local tmp = io.tmpfile()
tmp:write("Temporary data\n")
tmp:seek("set")
print("Temporary file content:", tmp:read("*l"))
tmp:close()

常用函数表

函数 描述 示例
io.open(filename [, mode]) 打开文件 io.open(“test.txt”, “r”)
io.input([file]) 设置或获取标准输入 io.input(“input.txt”)
io.output([file]) 设置或获取标准输出 io.output(“output.txt”)
io.read([format]) 从标准输入读取 io.read(“*l”)
io.write(…) 写入标准输出 io.write(“hello”)
io.tmpfile() 创建临时文件 local tmp = io.tmpfile()
io.type(obj) 检查是否为文件句柄 io.type(file) → “file”
io.flush() 刷新输出缓冲区 io.flush()
io.close([file]) 关闭文件 io.close(file)

文件操作模式

模式 描述
r 只读模式,文件必须存在
w 只写模式,覆盖现有文件或创建新文件
a 追加模式,在文件末尾添加内容或创建新文件
r+ 读写模式,文件必须存在
w+ 读写模式,覆盖现有文件或创建新文件
a+ 读写模式,在文件末尾添加内容或创建新文件
b 二进制模式(与其他模式组合使用)

读取格式

格式 描述
“*n” 读取一个数字
“*a” 读取整个文件
“*l” 读取一行(默认)
number 读取指定数量的字符

5. table 库(表操作)

table 库提供了表操作的功能,包括连接表元素、插入和删除元素、排序表、解包表等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- 5.1 table.concat(连接表元素)
local colors = {"red", "green", "blue"}
print("table.concat(colors, ', '):", table.concat(colors, ", "))

-- 5.2 table.insert 和 table.remove
local numbers = {1, 2, 3, 4, 5}
table.insert(numbers, 3, 100) -- 在索引3插入100
print("After table.insert(numbers, 3, 100):", table.concat(numbers, ", "))

local removed = table.remove(numbers, 3) -- 删除索引3的元素
print("After table.remove(numbers, 3):", table.concat(numbers, ", "))
print("Removed element:", removed)

-- 5.3 table.sort
local unsorted = {5, 2, 8, 1, 9, 3}
table.sort(unsorted)
print("table.sort(unsorted):", table.concat(unsorted, ", "))

-- 5.4 table.unpack
local coords = {10, 20, 30}
local x, y, z = unpack(coords)
print("unpack(coords):", x, y, z)

-- 5.5 表的遍历(ipairs和pairs)
local mixed = {"a", "b", name = "mixed", value = 100, "c"}
print("\nUsing ipairs (array part only):")
for i, v in ipairs(mixed) do
print(i, v)
end

print("\nUsing pairs (all elements):")
for k, v in pairs(mixed) do
print(k, v)
end

常用函数表

函数 描述 示例
table.concat(table [, sep [, i [, j]]]) 连接表元素 table.concat({“a”, “b”, “c”}, “, “) → “a, b, c”
table.insert(table, [pos,] value) 插入元素 table.insert({1, 2, 3}, 2, 10) → {1, 10, 2, 3}
table.remove(table [, pos]) 删除元素 table.remove({1, 10, 2, 3}, 2) → {1, 2, 3}
table.sort(table [, comp]) 排序表 table.sort({3, 1, 4, 2}) → {1, 2, 3, 4}
table.pack(…) 打包参数为表 table.pack(1, 2, 3) → {1, 2, 3, n=3}
unpack(table [, i [, j]]) 解包表为参数 unpack({1, 2, 3}) → 1, 2, 3

表的遍历

函数 描述 适用场景
ipairs(table) 遍历表的数组部分 只包含数字索引的表
pairs(table) 遍历表的所有元素 包含混合索引的表

6. debug 库(调试功能)

debug 库提供了调试功能,包括获取函数信息、查看全局环境、设置钩子等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
-- 6.1 获取当前函数名
function test_debug()
local info = debug.getinfo(1)
print("Current function name:", info.name)
print("Line number:", info.currentline)
end
test_debug()

-- 6.2 查看全局环境
print("\ndebug.getmetatable(_G):", debug.getmetatable(_G))

常用函数表

函数 描述 示例
debug.getinfo([thread,] level) 获取函数信息 debug.getinfo(1)
debug.getlocal([thread,] level, local) 获取局部变量 debug.getlocal(1, 1)
debug.setlocal([thread,] level, local, value) 设置局部变量 debug.setlocal(1, 1, 10)
debug.getupvalue(func, up) 获取上值 debug.getupvalue(func, 1)
debug.setupvalue(func, up, value) 设置上值 debug.setupvalue(func, 1, 10)
debug.getmetatable(value) 获取元表 debug.getmetatable(_G)
debug.setmetatable(value, table) 设置元表 debug.setmetatable({}, {})
debug.traceback([thread [, message [, level]]]) 获取堆栈跟踪 debug.traceback()
debug.sethook([thread,] hook, mask [, count]) 设置钩子 debug.sethook(print, “c”)
debug.gethook([thread]) 获取钩子 debug.gethook()

7. coroutine 库(协程)

coroutine 库提供了协程功能,包括创建协程、运行协程、挂起协程、检查协程状态等功能。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- 创建协程
local co = coroutine.create(function()
for i = 1, 3 do
print("Coroutine yielding:", i)
coroutine.yield(i)
end
return "Coroutine finished"
end)

-- 运行协程
print("Coroutine status:", coroutine.status(co))

local status, result = coroutine.resume(co)
print("Resume 1 - Status:", status, "Result:", result)
print("Coroutine status:", coroutine.status(co))

status, result = coroutine.resume(co)
print("Resume 2 - Status:", status, "Result:", result)

status, result = coroutine.resume(co)
print("Resume 3 - Status:", status, "Result:", result)

status, result = coroutine.resume(co)
print("Resume 4 - Status:", status, "Result:", result)
print("Coroutine status:", coroutine.status(co))

常用函数表

函数 描述 示例
coroutine.create(f) 创建协程 coroutine.create(function() end)
coroutine.resume(co [, …]) 运行或恢复协程 coroutine.resume(co)
coroutine.yield(…) 挂起协程 coroutine.yield(“value”)
coroutine.status(co) 检查协程状态 coroutine.status(co) → “suspended”
coroutine.wrap(f) 创建协程并返回函数 local co = coroutine.wrap(function() end)
coroutine.running() 获取当前运行的协程 coroutine.running()
coroutine.isyieldable() 检查是否可以挂起 coroutine.isyieldable()

协程状态

状态 描述
suspended 协程已创建但尚未运行,或已运行但被挂起
running 协程正在运行
dead 协程已执行完毕,或因错误而终止
normal 协程正在运行,但不是当前正在执行的协程

8. package 库(模块管理)

package 库提供了模块管理功能,包括模块的加载、搜索路径的设置等功能。

示例代码

1
2
3
print("package.path:", package.path)
print("package.cpath:", package.cpath)
print("package.loaded:", next(package.loaded))

常用函数表

函数 描述 示例
package.loaded 已加载的模块表 package.loaded.string
package.preload 预加载模块表 package.preload[“mymodule”] = function() end
package.path Lua模块搜索路径 package.path = package.path .. “;./?.lua”
package.cpath C模块搜索路径 package.cpath = package.cpath .. “;./?.dll”
package.loadlib(libname, funcname) 加载C库 package.loadlib(“mylib.dll”, “luaopen_mylib”)
require(modname) 加载模块 require(“mymodule”)

模块搜索路径

  • package.path:Lua 模块的搜索路径,格式为多个路径模板,用分号分隔
  • package.cpath:C 模块的搜索路径,格式与 package.path 类似

9. 实用工具函数

除了标准库提供的函数外,我们还可以创建一些实用的工具函数,来简化常见的操作。

9.1 字符串分割函数

1
2
3
4
5
6
7
8
9
10
11
function split(str, sep)
local result = {}
for part in string.gmatch(str, "[^" .. sep .. "]+") do
table.insert(result, part)
end
return result
end

local csv_str = "apple,banana,orange,grape"
local parts = split(csv_str, ",")
print("Split CSV:", table.concat(parts, " | "))

9.2 深拷贝函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else
copy = orig
end
return copy
end

local original = {a = 1, b = {c = 2}}
local copied = deepcopy(original)
copied.b.c = 100
print("Original.b.c:", original.b.c)
print("Copied.b.c:", copied.b.c)

9.3 表的长度(处理混合表)

1
2
3
4
5
6
7
8
9
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end

local mixed_table = {"a", "b", name = "test", value = 42}
print("#mixed_table:", #mixed_table) -- 只计算数组部分
print("tablelength(mixed_table):", tablelength(mixed_table)) -- 计算所有元素

10. 标准库最佳实践

10.1 字符串操作

  1. 使用 # 运算符获取字符串长度#strstring.len(str) 更简洁
  2. 合理使用字符串格式化string.format() 可以使字符串拼接更清晰
  3. 避免频繁字符串连接:对于大量字符串连接,使用表和 table.concat() 更高效
  4. 使用正则表达式时要注意性能:复杂的正则表达式可能会影响性能

10.2 数学运算

  1. 设置随机种子:在使用 math.random() 前,应该使用 math.randomseed(os.time()) 设置随机种子
  2. 注意浮点数精度:Lua 中的数字都是浮点数,要注意精度问题
  3. 使用合适的数学函数:根据需要选择合适的数学函数,如 math.floor()math.ceil()

10.3 文件操作

  1. 总是检查文件是否打开成功local file, err = io.open(filename, mode)
  2. 使用后关闭文件:文件操作完成后,应该调用 file:close() 关闭文件
  3. 使用 xpcall 确保资源清理:在处理需要使用资源的操作时,使用 xpcall 确保即使发生错误,资源也能被正确清理

10.4 表操作

  1. 使用 ipairs 和 pairs 进行遍历:根据表的类型选择合适的遍历函数
  2. 合理使用表的方法:根据需要选择合适的表操作函数,如 table.insert()table.remove()
  3. 注意表的内存使用:对于大型表,要注意内存使用情况

10.5 协程使用

  1. 合理使用协程:协程适用于需要暂停和恢复执行的场景,如 IO 操作
  2. 注意协程状态:在使用协程前,应该检查其状态
  3. 避免嵌套过深:嵌套过深的协程会使代码难以理解和维护

11. 常见问题与解决方案

11.1 字符串操作

问题:字符串连接效率低
解决方案:使用表和 table.concat() 进行大量字符串连接

1
2
3
4
5
6
7
8
9
10
11
12
-- 低效的方式
local result = ""
for i = 1, 1000 do
result = result .. i
end

-- 高效的方式
local parts = {}
for i = 1, 1000 do
parts[#parts + 1] = i
end
local result = table.concat(parts)

11.2 数学运算

问题:随机数每次运行都相同
解决方案:使用 math.randomseed(os.time()) 设置随机种子

1
2
math.randomseed(os.time())  -- 设置随机种子
print("Random number:", math.random())

11.3 文件操作

问题:文件打开失败
解决方案:检查文件是否存在,或使用 pcall() 捕获错误

1
2
3
4
5
6
7
local file, err = io.open("test.txt", "r")
if not file then
print("Error opening file:", err)
return
end
-- 文件操作...
file:close()

11.4 表操作

问题:表的长度计算不准确
解决方案:对于混合表,使用自定义函数计算长度

1
2
3
4
5
6
7
8
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end

local mixed_table = {"a", "b", name = "test", value = 42}
print("Table length:", tablelength(mixed_table))

11.5 模块管理

问题:模块找不到
解决方案:检查 package.pathpackage.cpath 是否包含模块所在的路径

1
2
3
print("package.path:", package.path)
-- 如果需要,添加路径
package.path = package.path .. ";./?.lua"

总结

本指南介绍了 Lua 中的标准库,包括 string、math、os、io、table、debug、coroutine 和 package 等库的使用方法。通过学习本指南,您应该已经掌握了 Lua 中标准库的基本使用技巧和最佳实践。

Lua 的标准库提供了丰富的功能,可以满足大多数编程需求。在实际应用中,您可以根据具体情况选择合适的库和函数,提高代码的效率和可读性。

希望本指南对您有所帮助,祝您在 Lua 编程中取得成功!

standard_lib.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
-- Lua标准库示例
-- print语句使用英语,注释使用中文

print("=== Lua Standard Library Example ===")

-- 1. string库(字符串操作)
print("\n1. string Library (String Operations)")

local str = "Hello, Lua Programming!"
print("Original string:", str)

-- 1.1 字符串长度
print("Length:", string.len(str))
print("Length (using #):", #str)

-- 1.2 字符串大小写转换
print("Uppercase:", string.upper(str))
print("Lowercase:", string.lower(str))

-- 1.3 字符串截取
print("Substring (1-5):", string.sub(str, 1, 5))
print("Substring (8-end):", string.sub(str, 8))
print("Substring (from end):", string.sub(str, -11))

-- 1.4 字符串查找
local start_pos, end_pos = string.find(str, "Lua")
print("Find 'Lua':", start_pos, end_pos)

-- 1.5 字符串替换
local new_str = string.gsub(str, "Lua", "LUA")
print("Replace 'Lua' with 'LUA':", new_str)

-- 1.6 字符串格式化
local formatted = string.format("%s is %d years old and has %.2f GPA", "Alice", 25, 3.85)
print("Formatted string:", formatted)

-- 1.7 字符串重复
print("Repeat 'Hi ' 3 times:", string.rep("Hi ", 3))

-- 1.8 字符串匹配(正则表达式)
local email = "user@example.com"
local username = string.match(email, "(%a+)@")
local domain = string.match(email, "@(%a+%.%a+)")
print("Email parts - username:", username, "domain:", domain)

-- 1.9 字符串分割(使用gmatch)
local csv = "apple,banana,orange,grape"
local fruits = {}
for fruit in string.gmatch(csv, "[^,]+") do
table.insert(fruits, fruit)
end
print("Split CSV:", table.concat(fruits, " | "))

-- 2. math库(数学函数)
print("\n2. math Library (Mathematical Functions)")

-- 2.1 基本数学运算
print("math.abs(-10):", math.abs(-10))
print("math.floor(3.7):", math.floor(3.7))
print("math.ceil(3.2):", math.ceil(3.2))
print("math.sqrt(16):", math.sqrt(16))

-- 2.2 三角函数
print("math.sin(math.pi/2):", math.sin(math.pi/2))
print("math.cos(math.pi):", math.cos(math.pi))
print("math.tan(math.pi/4):", math.tan(math.pi/4))
print("math.asin(1):", math.asin(1))

-- 2.3 指数和对数
print("math.exp(1):", math.exp(1))
print("math.log(math.exp(1)):", math.log(math.exp(1)))
print("math.log10(100):", math.log10(100))
print("math.pow(2, 10):", math.pow(2, 10))

-- 2.4 最大最小值
print("math.max(10, 5, 20, 15):", math.max(10, 5, 20, 15))
print("math.min(10, 5, 20, 15):", math.min(10, 5, 20, 15))

-- 2.5 随机数
math.randomseed(os.time()) -- 设置随机种子
print("Random (0-1):", math.random())
print("Random (1-10):", math.random(10))
print("Random (5-15):", math.random(5, 15))

-- 2.6 常量
print("math.pi:", math.pi)
print("math.huge:", math.huge)

-- 3. os库(操作系统交互)
print("\n3. os Library (Operating System Interaction)")

-- 3.1 时间函数
print("os.time():", os.time())
print("os.date():", os.date())
print("os.date('%Y-%m-%d'):", os.date("%Y-%m-%d"))
print("os.date('%H:%M:%S'):", os.date("%H:%M:%S"))

-- 3.2 执行系统命令
print("\nExecute system command 'echo Hello':")
local handle = io.popen("echo Hello")
if handle then
local result = handle:read("*a")
print("Result:", result)
handle:close()
end

-- 3.3 获取环境变量
print("\nos.getenv('PATH'):", os.getenv("PATH"))

-- 3.4 其他os函数
print("os.clock():", os.clock())
print("os.difftime(os.time(), os.time() - 3600):", os.difftime(os.time(), os.time() - 3600))

-- 4. io库(文件操作补充)
print("\n4. io Library (File Operations)")

-- 4.1 标准输入输出
print("\nStandard I/O:")
-- io.write("Enter your name: ")
-- local name = io.read()
-- print("Hello, " .. name)

-- 4.2 临时文件
local tmp = io.tmpfile()
tmp:write("Temporary data\n")
tmp:seek("set")
print("Temporary file content:", tmp:read("*l"))
tmp:close()

-- 5. table库(表操作补充)
print("\n5. table Library (Table Operations)")

-- 5.1 table.concat(连接表元素)
local colors = {"red", "green", "blue"}
print("table.concat(colors, ', '):", table.concat(colors, ", "))

-- 5.2 table.insert 和 table.remove
local numbers = {1, 2, 3, 4, 5}
table.insert(numbers, 3, 100) -- 在索引3插入100
print("After table.insert(numbers, 3, 100):", table.concat(numbers, ", "))

local removed = table.remove(numbers, 3) -- 删除索引3的元素
print("After table.remove(numbers, 3):", table.concat(numbers, ", "))
print("Removed element:", removed)

-- 5.3 table.sort
local unsorted = {5, 2, 8, 1, 9, 3}
table.sort(unsorted)
print("table.sort(unsorted):", table.concat(unsorted, ", "))

-- 5.4 table.unpack
local coords = {10, 20, 30}
local x, y, z = unpack(coords)
print("unpack(coords):", x, y, z)

-- 5.5 表的遍历(ipairs和pairs)
local mixed = {"a", "b", name = "mixed", value = 100, "c"}
print("\nUsing ipairs (array part only):")
for i, v in ipairs(mixed) do
print(i, v)
end

print("\nUsing pairs (all elements):")
for k, v in pairs(mixed) do
print(k, v)
end

-- 6. debug库(调试功能)
print("\n6. debug Library (Debugging Functions)")

-- 6.1 获取当前函数名
function test_debug()
local info = debug.getinfo(1)
print("Current function name:", info.name)
print("Line number:", info.currentline)
end
test_debug()

-- 6.2 查看全局环境
print("\ndebug.getmetatable(_G):", debug.getmetatable(_G))

-- 7. coroutine库(协程)
print("\n7. coroutine Library (Coroutines)")

-- 创建协程
local co = coroutine.create(function()
for i = 1, 3 do
print("Coroutine yielding:", i)
coroutine.yield(i)
end
return "Coroutine finished"
end)

-- 运行协程
print("Coroutine status:", coroutine.status(co))

local status, result = coroutine.resume(co)
print("Resume 1 - Status:", status, "Result:", result)
print("Coroutine status:", coroutine.status(co))

status, result = coroutine.resume(co)
print("Resume 2 - Status:", status, "Result:", result)

status, result = coroutine.resume(co)
print("Resume 3 - Status:", status, "Result:", result)

status, result = coroutine.resume(co)
print("Resume 4 - Status:", status, "Result:", result)
print("Coroutine status:", coroutine.status(co))

-- 8. package库(模块管理)
print("\n8. package Library (Module Management)")

print("package.path:", package.path)
print("package.cpath:", package.cpath)
print("package.loaded:", next(package.loaded))

-- 9. 实用工具函数
print("\n9. Utility Functions")

-- 9.1 字符串分割函数
function split(str, sep)
local result = {}
for part in string.gmatch(str, "[^" .. sep .. "]+") do
table.insert(result, part)
end
return result
end

local csv_str = "apple,banana,orange,grape"
local parts = split(csv_str, ",")
print("Split CSV:", table.concat(parts, " | "))

-- 9.2 深拷贝函数
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else
copy = orig
end
return copy
end

local original = {a = 1, b = {c = 2}}
local copied = deepcopy(original)
copied.b.c = 100
print("Original.b.c:", original.b.c)
print("Copied.b.c:", copied.b.c)

-- 9.3 表的长度(处理混合表)
function tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end

local mixed_table = {"a", "b", name = "test", value = 42}
print("#mixed_table:", #mixed_table) -- 只计算数组部分
print("tablelength(mixed_table):", tablelength(mixed_table)) -- 计算所有元素

print("\n=== End of Standard Library Examples ===")